Ajax請求全域配置

來源:互聯網
上載者:User

標籤:

摘要:

  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|divide|#247);/g,        entity = {        ‘&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;‘   : ‘ב,        ‘&divide;‘ : ‘÷‘,        ‘&#247;‘   : ‘÷‘    };    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: ‘‘}))

 

Ajax請求全域配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.