前端手写(二十)——手写ajax

x33g5p2x  于2022-04-02 转载在 其他  
字(0.6k)|赞(0)|评价(0)|浏览(180)

一、写在前面
ajax在前后端数据交互的过程中,起着比较重要的作用,而且在面试过程中也是比较常问的一个问题,下面我们将手动封装一个ajax
二、手动封装

const getJSON = function (url) {
      return new Promise((resolve, reject) => {
        const xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Mscrosoft.XMLHttp');
        xhr.open('GET', url, false);
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.onreadystatechange = function () {
          if (xhr.readyState !== 4) return;
          if (xhr.status === 200 || xhr.status === 304) {
            resolve(xhr.responseText);
          } else {
            reject(new Error(xhr.responseText));
          }
        }
        xhr.send();
      })
    }

    getJSON('http://123.207.32.32:8000/home/multidata').then(res => {
      console.log(res)
    })

相关文章

微信公众号

最新文章

更多