原生ajax请求和promise ajax请求实现
侧边栏壁纸
  • 累计撰写 12 篇文章
  • 累计收到 0 条评论

原生ajax请求和promise ajax请求实现

liangzai
2023-08-31 / 0 评论 / 14 阅读 / 正在检测是否收录...

原生ajax实现

const url = "/user/login";
let xhr = new XMLHttpRequest();
// 创建 Http 请求
xhr.open("GET", url, true);
// 设置状态监听函数
xhr.onreadystatechange = function() {
  if (this.readyState !== 4) return;
  // 当请求成功时
  if (this.status === 200) {
    handle(this.response);
  } else {
    console.error(this.statusText);
  }
};
// 设置请求失败时的监听函数
xhr.onerror = function() {
  console.error(this.statusText);
};
// 设置请求头信息
xhr.responseType = "json";
xhr.setRequestHeader("Accept", "application/json");
// 发送 Http 请求
xhr.send(null);

promise ajax实现
1、前端可以通过getData(url).then(res=>{console.log(res即为获取到的数据)})
2、通过 async await方式

const dataJson = async()=>{
    let res = await getData(url)
    console.log(res);//res即为后台返回的数据
}
// promise 封装实现:
function getData(url) {
  // 创建一个 promise 对象
  let promise = new Promise(function(resolve, reject) {
    let xhr = new XMLHttpRequest();
    // 新建一个 http 请求
    xhr.open("GET", url, true);
    // 设置状态的监听函数
    xhr.onreadystatechange = function() {
      if (this.readyState !== 4) return;
      // 当请求成功或失败时,改变 promise 的状态
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
    // 设置错误监听函数
    xhr.onerror = function() {
      reject(new Error(this.statusText));
    };
    // 设置响应的数据类型
    xhr.responseType = "json";
    // 设置请求头信息
    xhr.setRequestHeader("Accept", "application/json");
    // 发送 http 请求
    xhr.send(null);
  });
  return promise;
}
1

评论 (0)

取消