[Promise]封装Ajax请求

 <script>
      function sendAjax(url) {
        return new Promise((resolve, reject) => {
          // 创建对象
          const xhr = new XMLHttpRequest();
          //修改响应体的格式
          xhr.responseType = "json";
          // 初始化
          xhr.open("GET", url);
          // 发送请求
          xhr.send();
          // 绑定事件处理响应结果
          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
              if (xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.response);
              } else {
                reject(xhr.status);
              }
            }
          };
        });
      }
      sendAjax("http://gmall-h5-api.atguigu.cn/api/product/getBaseCategoryList")
        .then((value) => {
          console.log(value);
        })
        .catch((reason) => {
          console.log(reason);
        });
    </script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Promise封装 AJAX 请求。下面是一个示例: ```javascript function request(url, method, data) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open(method, url, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 400) { resolve(xhr.response); } else { reject(xhr.statusText); } }; xhr.onerror = function() { reject(xhr.statusText); }; xhr.send(JSON.stringify(data)); }); } ``` 使用示例: ```javascript request('https://api.example.com/data', 'POST', { foo: 'bar' }) .then(function(response) { console.log('请求成功', response); }) .catch(function(error) { console.error('请求失败', error); }); ``` 在封装的 `request` 函数中,我们创建了一个新的 Promise 对象,并在 AJAX 请求的 `onload` 和 `onerror` 事件处理程序中处理成功和失败的情况。如果请求成功,我们调用 `resolve` 方法并传递响应数据,如果请求失败,我们调用 `reject` 方法并传递错误状态信息。 在使用时,我们可以通过链式调用 `.then()` 和 `.catch()` 方法来处理异步请求的结果。`.then()` 方法接收一个回调函数,当请求成功时会调用该函数,并传递响应数据。`.catch()` 方法接收一个回调函数,当请求失败时会调用该函数,并传递错误信息。 这样,我们就可以使用 Promise封装 AJAX 请求,并通过链式调用来处理异步请求的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值