promise封装ajax

本文介绍了一个使用原生JavaScript实现的简易版Axios库,包括GET和POST请求的发送,以及超时处理。该库通过Promise进行异步操作管理,并能够处理请求参数的序列化。
const axios = function(options){
    let promise = new promise(( resolve , reject )=>{
        var xhr = null;
        if(window.XMLHttpRequest){//兼容处理
           xhr = new XMLHttpRequest();
       }else{
           xhr = new ActiveXObject("Microsoft.XMLHTTP");   
       }
         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;
}    

栗子:

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

 

转载于:https://www.cnblogs.com/wildccy/p/10543154.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值