axios的封装

function axios(options){
    var promise = new Promise((resolve,reject)=>{
        var xhr = null;
        if(window.XMLHttpRequest){
            xhr = new XMLHttpRequest();
        }else{
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        var str = "";
        //进行传入数据的处理
        for(var key in options.data){
            str += "&" + key + "=" + options.data[key];
        }
        if(options.method == "get"){
            var url = options.url + "?" + data.slice(1);//因为在前面将传入的数据多加了一个&符号,然而需要的是&之后的数据
            xhr.open(options.method,url);
            xhr.send();//通过get方式请求数据不需要发送数据
        }else if(options.method == "post"){
            xhr.open(options.method,options.url);
            xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
            xhr.send(str);
        }
        xhr.onreadystatechange = function(){
            var timer = null;
            //timeout是ajax请求中的一个默认属性,表示时间。如果该默认属性存在则使用默认值,否则使用5000毫秒
            var timeout = options.timeout?options.timeout:5000;
            if(xhr.readState == 4 && xhr.status == 200){
                var res = JSON.parse(xhr.responseText);
                clearTimeout(timer);
                resolve(res);
            }
            timer = setTimeout(()=>{
                clearTimeout(timer);
                reject(xhr.status);
            },timeout);
        }
    })
    return promise;
}

 

posted @ 2019-03-22 10:42  leslie-cheung  阅读(178)  评论(0编辑  收藏  举报