javaScript 用Promise封装Ajax请求

//封装一个sendAJAX发送 GET AJAX请求
//参数URL
//返回结果Prommise对象
function sendAJAX(url) {
    
    
  return new Promise((resolve, reject) => {
    
    
    const xml =new XMLHttpRequest()
    xml.responseType='json'//设置响应类型为json
    xml.open('GET', url) //打开请求
    xml.send() //发送请求
    //处理请求结果
    xml.onreadystatechange = function () {
    
    
      if (xml.readState === 4) {
    
    
        //请求完成
        if (xml.status >= 200 && xml.status < 300) {
    
    
          //请求成功
          resolve(xml.response)//返回响应数据
        } //请求失败
        else {
    
    
          reject(xml.status)//返回状态码
        }
      }
    }
  })
}


猜你喜欢

转载自blog.csdn.net/m0_58065010/article/details/129784780