zoukankan      html  css  js  c++  java
  • promise 封装 axios

    /*axios({
      method:"get",
      url:"./data.json",
      data:{
        id:10
      }
    }).then((res)=>{
      console.log(res)
    },(e)=>{
      console.log(e);
    })*/

    function axios(options) {
      let promise = new Promise((resolve, reject) => {  
        var xhr = new XMLHttpRequest();
        var data = "";
        //数据处理

        for (var key in options.data) {
        data += "&" + key + "=" + options.data[key]
        }

        if (options.method == "get") {

          let url = options.url + "?" + data.slice(1);
          xhr.open(options.method, url);
          xhr.send();
        } else if (options.method == "post") {

          xhr.open(options.method, options.url);
          xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
          xhr.send(data);
        }


        xhr.onreadystatechange = function () {
          let timer = null;
          let timeout = options.timeout?options.timeout:5000
          if(xhr.readyState == 4 && xhr.status == 200){
            let res = JSON.parse(xhr.responseText);
            clearTimeout(timer);
            resolve(res);
          }

         timer = setTimeout(()=>{
           clearTimeout(timer);
              reject(xhr.status);
            },timeout)

        }
      })
      return promise;
    }

  • 相关阅读:
    开始Flask项目
    夜间模式的开启与关闭,父模板的制作
    从首页问答标题到问答详情页
    首页列表显示全部问答,完成问答详情页布局
    制作首页的显示列表
    发布功能完成
    登录之后更新导航
    完成登录功能,用session记住用户名
    完成注册功能
    通过用户模型,对数据库进行增删改查操作
  • 原文地址:https://www.cnblogs.com/wangqi2019/p/10543395.html
Copyright © 2011-2022 走看看