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

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

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

  1. const getJSON = function (url) {
  2. return new Promise((resolve, reject) => {
  3. const xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Mscrosoft.XMLHttp');
  4. xhr.open('GET', url, false);
  5. xhr.setRequestHeader('Accept', 'application/json');
  6. xhr.onreadystatechange = function () {
  7. if (xhr.readyState !== 4) return;
  8. if (xhr.status === 200 || xhr.status === 304) {
  9. resolve(xhr.responseText);
  10. } else {
  11. reject(new Error(xhr.responseText));
  12. }
  13. }
  14. xhr.send();
  15. })
  16. }
  17. getJSON('http://123.207.32.32:8000/home/multidata').then(res => {
  18. console.log(res)
  19. })

相关文章