ajax

ajax请求封装(基于jquery)

/**
 * ajax请求封装
 * @param method 请求方式
 * @param url api地址
 * @param data 参数
 * @param success 请求成功的回调
 * @param error 请求错误的回调
 */
function ajax(method, url, data, success, error) {
    var default_config = {
        url: domain.main + url,
        dataType: "json",
        async: false,
        data: data,
        type: method || 'GET',
        cache: false,
        headers: {
            'X-Token': localStorage.token
        },
        crossDomain: true,
        // 请求前的处理
        beforeSend: function () {
        },
        success: function (data) {
            success = typeof success === 'function' ? success : function (err) {
            };
            success(data);
        },
        complete: function (data) {
            var res;
            res = JSON.parse(data.responseText);
            if (data.status == '200') {
                data.success(res);
            } else {
                data.error(data.status, data.statusText, res);
            }
        },
        error: function (err_data, err_id, err) {
            if (err_data.status == '401' && JSON.parse(err_data.responseText).meta.message == "登录验证失败") {
                console.log(JSON.parse(err_data.responseText).meta.message + ',请重新登录');
                localStorage.clear();
                layui.use('layer', function () {
                    var layer = layui.layer;
                    layer.open({
                        content: JSON.parse(err_data.responseText).meta.message + ',请重新登录',
                        btn: ['确认'],
                        yes: function (index) {
                            var url = window.location.href;
                            localStorage.url = url;
                            location.href = "/views/sign/signin.html?sign=signin";
                        }
                    });
                });
            } else if (err_data.status == '400') {
                console.log('错误信息:400,', JSON.parse(err_data.responseText).meta.message);
                layer.open({
                    content: '错误信息:400,' + JSON.parse(err_data.responseText).meta.message,
                    skin: 'msg',
                    time: 2
                })
            } else if (err_data.status == '404') {
                console.log('错误信息:404,', JSON.parse(err_data.responseText).meta.message);
                layer.open({
                    content: '错误信息:404,请求超时,请重试',
                    skin: 'msg',
                    time: 2
                })
            } else if (err_data.status == '500') {
                console.log('错误信息:500,服务器出错,请稍后再试' + JSON.parse(err_data.responseText).meta.message);
                layer.open({
                    content: '错误信息:500,服务器出错,请稍后再试',
                    skin: 'msg',
                    time: 2
                })
                layer.alert(JSON.parse(err_data.responseText).meta.message);
            } else if (err_data.status == '502') {
                console.log('错误信息:502,服务器出错,请稍后再试' + JSON.parse(err_data.responseText).meta.message);
                layer.open({
                    content: '错误信息:502,服务器出错,请稍后再试',
                    skin: 'msg',
                    time: 2
                })
            }
            error = typeof error === 'function' ? error : function (err) {
            };
            error(err_data.status, err_id, err);
        }
    };
    $.ajax(default_config);
}

原生js的ajax封装


/* 封装ajax函数
* @param {string}opt.type http连接的方式,包括POSTGET两种方式
* @param {string}opt.url 发送请求的url
* @param {boolean}opt.async 是否为异步请求,true为异步的,false为同步的
* @param {object}opt.data 发送的参数,格式为对象类型
* @param {function}opt.success ajax发送并接收成功调用的回调函数
*/
function ajax(opt) {
opt = opt || {};
opt.method = opt.method.toUpperCase() || 'POST';
opt.url = opt.url || '';
opt.async = opt.async || true;
opt.data = opt.data || null;
opt.success = opt.success || function () {};
var xmlHttp = null;
if (XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
var params = [];
for (var key in opt.data) {
params.push(key + '=' + opt.data[key]);
}
var postData = params.join('&');
if (opt.method.toUpperCase() === 'POST') {
xmlHttp.open(opt.method, opt.url, opt.async);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
xmlHttp.send(postData);
}
else if (opt.method.toUpperCase() === 'GET') {
xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
xmlHttp.send(null);
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
opt.success(xmlHttp.responseText);
}
}
};






    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            opt.success(xmlHttp.responseText);
        }
    }
























posted @ 2018-02-28 10:15  minimissile  阅读(166)  评论(0编辑  收藏  举报