gpt4 book ai didi

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

转载 作者:知者 更新时间:2024-03-13 03:00:46 24 4
gpt4 key购买 nike

一、写在前面
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)
    })

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com