ajax封装成以promise风格调用

本文档展示了如何将Ajax请求封装成Promise风格,便于异步操作管理。通过创建axios对象,定义了配置项如请求头、超时时间和异步设置,并提供了get和post方法进行HTTP请求。在请求过程中,设置了状态改变、超时和错误处理的回调,当请求成功时返回解析后的JSON数据,失败时返回错误信息。

ajax封装成以promise风格调用

ajax详细用法请点击以下链接

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/onreadystatechange

// 封装ajax请求
    const axios = {
      config: {
        header: { "Content-Type": "application/json; charset=utf-8" },
        timeout: 10000,
        async: true
      },
      setConfig({
        header = {},
        timeout = 10000,
        async = true
      }) {
        this.config.header = { ... this.config.header, ...header };
        this.config.timeout = timeout;
        this.config.async = async;
        return this;
      },
      init(method, url, data) {
        let { header, timeout, async } = this.config, flag = ["GET", "DELETE"].includes(method);
        return new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest();
          flag ? xhr.open(method, `${url}?${Object.keys(data).map(key => `${key}=${data[key]}`).join("&")}`, async) : xhr.open(method, url, async);
          // 设置超时时间 10秒
          xhr.timeout = timeout;
          // 设置请求头
          Object.keys(header).forEach(k => {
            xhr.setRequestHeader(k, header[k]);
          })
          flag ? xhr.send() : xhr.send(JSON.stringify(data));
          xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && xhr.status == 200) {
              resolve(JSON.parse(xhr.responseText))
            }
          }
          xhr.ontimeout = () => {
            reject("请求超时")
          }
          // xhr.onload = () => {
          //   console.log("请求完成")
          // }
          xhr.onerror = err => {
            reject("请求出错")
          }
        })
      },
      get(url, data = {}) {
        return this.init("GET", url, data);
      },
      post(url, data = {}) {
        return this.init("POST", url, data);
      }
    }
    // 发个请求试试
    axios.setConfig({
      header: {
        "token": "123456"
      }
    }).get("https://v1.hitokoto.cn?encode=json").then(data => {
      console.log(data)
    }, errMsg => {
      console.log(errMsg)
    })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值