zoukankan      html  css  js  c++  java
  • vue框架中的Axios封装

     
    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;
    }
  • 相关阅读:
    【java】一维数组循环位移方阵
    【java】for循环输出数字金字塔
    C++编程tips
    C++中cin.get 和cin.peek 及其相关的用法
    ubuntu增加字符设备驱动程序/ 操作系统课程设计
    C++ Primer 学习笔记/ 处理类型
    C++学习,顶层const
    C++学习笔记/const和指针
    ubuntu16.04增加系统调用(拷贝)
    Java学习笔记#数组 循环遍历
  • 原文地址:https://www.cnblogs.com/xuazi-7an/p/10640416.html
Copyright © 2011-2022 走看看