ajax封装成以promise风格调用

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)
    })
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值