ajax封装

2019-11-04  本文已影响0人  小北酱丶
// ajax封装
var HttpRequest = function (options) {
    var defaults = {
        type: 'get',
        headers: {},
        data: {},
        dataType: 'json',
        async: true,
        cache: false,
        beforeSend: null,
        success: null,
        complete: null
    };
    var o = $.extend({}, defaults, options);
    $.ajax({
        url: o.url,
        type: o.type,
        headers: {
            'Content-Type': o.contentType,
            'Authorization': 'token '+o.token
        },
        data: o.data,
        dataType: o.dataType,
        async: o.async,
        beforeSend: function () {
            o.beforeSend && o.beforeSend();
        },
        success: function (res) {
            o.success && o.success(res);
        },
        complete: function () {
            o.complete && o.complete();
        }
    });
};
// 登入页无需携带token
var loginHttp = function (options) {
    // 后台如果要求 Content-Type 
    if (options.type == 'post') {
        options.contentType = 'application/x-www-form-urlencoded';
    }
    HttpRequest(options);
}
//携带token请求
var ajaxHttp = function (options) {
    if (options.type == 'post') {
        options.contentType = 'application/x-www-form-urlencoded';
    }
    // 每次请求携带token
    var useInfo = JSON.parse(localStorage.getItem('useInfo'));
    if (useInfo){
        options.token = useInfo.Ticket
    }else{
        options.token =""
    }
    
    HttpRequest(options);
}

从别人页面搬过来的 只用于自己用

上一篇下一篇

猜你喜欢

热点阅读