封裝瞭jQuery的Ajax請求全局配置

  jQuery已經成為項目中最常見的js庫,也是前端開發最喜歡使用的庫。下面是在項目中封裝瞭jQuery的Ajax,分享給大傢。

代碼:

 

代碼如下:

// ajax 請求參數
var ajaxSettings = function(opt) {
    var url = opt.url;
    var href = location.href;
    // 判斷是否跨域請求
    var requestType = 'jsonp';
    if (url.indexOf(location.host) > -1)
        requestType = 'json';
    requestType = opt.dataType || requestType;
    // 是否異步請求
    var async = (opt.async === undefined ? true : opt.async);
    return {
        url: url,
        async: async,
        type: opt.type || 'get',
        dataType: requestType,
        cache: false,
        data: opt.data,
        success: function(data, textStatus, xhr) {
            /*
            *如果dataType是json,怎判斷返回數據是否為json格式,如果不是進行轉換
            * 成功數據通用格式
            *   {
            *       "code": 200,
            *       "data": [],
            *       "success": true // 成功
            *   }
            *   失敗返回的數據
            *   {
            *       "code": 200,
            *       "info": 'error',
            *       "success": false // 失敗
            *   }
             */
            if((requestType === 'json' || requestType === "jsonp") && typeof(data) === "string") {
                data = JSON.parse(data);
            }
            if(data.success) {
                opt.success(data);
            }

 

            if(opt.error) {
                opt.error(data);
            }

        },
        error: function(xhr, status, handler) {
            if (opt.error)
                opt.error();
        }
    };
};
function unescapeEntity(str) {
    var reg = /&(?:nbsp|#160|lt|#60|gt|62|amp|#38|quot|#34|cent|#162|pound|#163|yen|#165|euro|#8364|sect|#167|copy|#169|reg|#174|trade|#8482|times|#215|pide|#247);/g,
        entity = {
        ' '   : ' ',
        ' '   : ' ',
        '<'     : '<',
        '<'    : '<',
        '>'     : '>',
        '&62;'     : '>',
        '&'    : '&',
        '&'    : '&',
        '"'   : '"',
        '"'    : '"',
        '¢'   : '¢',
        '¢'   : '¢',
        '£'  : '£',
        '£'   : '£',
        '¥'    : '¥',
        '¥'   : '¥',
  &nbsnbsp;     '€'   : '€',
        '€'  : '€',
        '§'   : '§',
        '§'   : '§',
        '©'   : '©',
        '©'   : '©',
        '®'    : '®',
        '®'   : '®',
        '™'  : '™',
        '™'  : '™',
        '×'  : '×',
        '×'   : '×',
        '&pide;' : '&pide;',
        '&pide;'   : '&pide;'
    };
    if (str === null) {
        return '';
    }
    str = str.toString();
    return str.indexOf(';') < 0 ? str : str.replace(reg, function(chars) {
        return entity[chars];
    });
}
// 轉換html的實體
$.ajaxSetup({
    global     : true,
    cache      : false,
    converters : {
        'text json' : function(response){
            return jQuery.parseJSON(unescapeEntity(response));
        }
    }
});
/*
*Ajax 請求權限異常
*   用戶權限錯誤跳轉登陸頁
*   404錯誤跳轉404頁面
 */
$(document).ajaxComplete(function(evt, req, settings){
    if(req && req.responseJSON){
        var json = req.responseJSON;
        if(json.code === 403 && json.info === 'perm error' && !json.success){
            window.location.href = location.protocol + '//' + location.hostname;
            return;
        }
        if(json.code === 404 && !json.success) {
            window.location.href = location.protocol + '//' + location.hostname + '/404.html';
        }
    }
});
/*
*Ajax 請求錯誤提示
*例如:500錯誤
*返回錯誤信息格式
*{
*   code: 500,
*   info: 系統發生異常
*}
 */
$(document).ajaxError(function(evt, req, settings){
    if(req && (req.status === 200||req.status === 0)){ return false; }
    var msg = '錯誤:';
    if(req && req.responseJSON){
        var json = req.responseJSON;
        msg += json.code||'';
        msg += json.info||'系統異常,請重試';
    }else{
        msg = '系統異常,請重試';
    }
    alert(msg);
});

 

小結:

  在執行Ajax請求時隻需要調用ajaxSettings函數即可,如下:

 

代碼如下:

$.ajax(ajaxSettings({
    url: '',
    data: ''
}))

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *