手写Promise版本的 ajax请求

66 阅读1分钟

xhr 具有以下常用属性:

responseText: 请求返回的数据内容

responseXML: 如果响应内容是"text/xml""application/xml",这个属性将保存响应数据的 XML DOM文档

status: 响应的HTTP状态,如 200 304 404 等

statusText: HTTP状态说明

readyState: 请求/响应过程的当前活动阶段

timeout: 设置请求超时时间

  1. xhr.readyState==0 尚未调用 open 方法
  2. xhr.readyState==1 已调用 open 但还未发送请求(未调用 send)
  3. xhr.readyState==2 已发送请求(已调用 send)
  4. xhr.readyState==3 已接收到请求返回的数据
  5. xhr.readyState==4 请求已完成
    function sendAjax(url) {
      return new Promise((res, rej) => {

        //创建对象
        const x = new XMLHttpRequest();
        //初始化
        x.open('GET', url)
        //发送
        x.send()
        //事件绑定
        x.onreadystatechange = function () {
          if (x.readyState === 4) {
            if (x.status >= 200 && x.status < 300) {
              res(x.response)
            } else {
              rej(x.status)
            }
          }
        }
      })
    }
    //测试
    // sendAjax('https://api.apiopen.top/getJoke').then(res => {
    //   console.log(res)
    // })
    async function main() {
      const result = await sendAjax('http://www.yiketianqi.com/api?version=v9&appid=23035354&appsecret=8YvlPNrz')
      console.log(JSON.parse(result))
    }
    main()