ajax与promise

原生js发送请求

// 格式化post提交数据
var formateParams=function(data, isCache) { 
    var arr = []; 
    for(var name in data) {  
        arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name])); 
    } 
    if(isCache) {  
        arr.push('v=' + (new Date()).getTime()); 
    } 
    return arr.join('&');
}
//promise 封装xhr请求数据
var ajaxPro = function(param) {
    var data = {
        username: '179999999',
        password: '666666'
    }
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', param.url, true);
        xhr.onload = function() {
            if(xhr.readyState == 4 && xhr.status == 200) {
                resolve(JSON.parse(xhr.responseText));
            } else {
                params.error && params.error(status);
            }
        }
        xhr.onerror = function() {
            reject(JSON.parse(xhr.responseText));
        }
        // 非常重要,如果用post方式提交,必须加上请求头
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        //只有按照这个格式,后台才能收到数据username=179999999&password=666666
        xhr.send(formateParams(data));
    })
}
// 调用示例
var p = ajaxPro({ 
    url: '' // 要获取的文件地址
});
p.then(function(response) {
    console.log(response);
}).catch(function(err) {
    console.log(err);
});
            

封装jquery的ajax方法

function loading(){
    console.log('loading');
}
function stopLoading(){
    console.log('stopLoading');
}
var ajaxPro = function(param) {
    const APIURL = '';
    var options = {
        url: APIURL + param.url,
        type: param.type || 'POST',
        data: param.data,
        before: param.before || loading,
        complete: param.complete || stopLoading
    }
    return new Promise(function(resolve, reject) {
        $.ajax({
            url: options.url,
            type: options.type,
            data: options.data,
            beforeSend: options.before,
            complete: options.complete,
            success: function(data) {
                resolve(data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
            /**第一个参数
            *readyState :当前状态,0-未初始化,1-正在载入,2-已经载入,3-数据进行交互,4-完成
            *status  :返回的HTTP状态码,比如常见的404,500等错误代码。
            *statusText :对应状态码的错误信息,比如404错误信息是not found,500是Internal Server Error。
            *responseText :服务器响应返回的文本信息
            */ 
            
            /**第二个参数返回的状态
            *"timeout"(超时), "error"(错误), "abort"(中止), "parsererror"(解析错误),还有可能返回空值
            *字符串类型,表示服务器抛出返回的错误信息
            */
                var errInfo = {
                    jqXHR:jqXHR,
                    textStatus:textStatus,
                    errorThrown:errorThrown
                }
                reject(errInfo)
            }
        });
    });
};
// 调用示例
var p2 = ajaxPro({
    url: '/Home/User/login',
    data: {
        username: "17999999999",
        password: '666666'
    }
}).then(function(data) {
    console.log(data);
}).catch(function(err) {
    console.log(err);
});

封装mui.ajax

var appUI = {
    showWaiting: function() {
        plus.nativeUI.showWaiting();
    },
    closeWaiting: function() {
        plus.nativeUI.closeWaiting()
    }
}

function request(parm) {
    // 参数MD5加密
    return new Promise(function(resolve, reject) {
        // 接口域名
        const APIURL = '';
        var options = {
            type: param.type || 'POST',
            url:APIURL+param.url||'',
            data: param.data,
            dataType: param.dataType || 'json',
            timeout:param.timeout||60000,
            before: param.before || appUI.showWaiting,
            complete: param.complete || appUI.closeWaiting
        }
        mui.ajax(options.url, {
            data: options.data,
            dataType: options.dataType, //要求服务器返回json格式数据
            type: options.type, //HTTP请求类型,要和服务端对应,要么GET,要么POST
            timeout: options.timeout, //超时时间设置为6秒;
            beforeSend: options.before,
            complete: options.complete,
            success: function(data) {
                options.complete();
                if(data && data.code && data.code != undefined) {
                    resolve(data);
                } else {
                    mui.toast("服务器繁忙,请稍后再试");
                }
            },
            error: function(xhr, type, errorThrown) {
                // type:错误描述,类型是String,可取值除了'null'外,其它可能值:"timeout", "error", "abort", "parsererror" 
                options.complete();
                if(type == 'timeout' || type == 'abort') {
                    mui.toast("请求超时:请检查网络:" + type)
                } else {
                    mui.toast("服务器累了:" + type)
                }
                 var errInfo = {
                    xhr:xhr,
                    type:type,
                    errorThrown:errorThrown
                }
                reject(errInfo)
            }
        });
    })

}

参考博客

ajax
promise改写ajax
promise改写ajax
ajax博客园

转载于:https://www.cnblogs.com/bonly-ge/p/9871014.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值