DIV CSS 佈局教程網

jQuery Ajax 全域封裝實戰:跨域判斷、統一回傳格式與錯誤攔截
編輯:JQuery特效代碼     

為什麼值得多包一層

幾乎每個專案都離不開 jQuery,而 $.ajax 雖然功能完整,參數卻相當繁瑣。如果每個開發者都自己拼一次設定,最後就會出現「同一個專案、十種寫法」的局面:有人忘了關閉快取,有人沒有處理登入逾時,有人把錯誤訊息直接丟給使用者看。

比較務實的做法,是把請求方式、資料型別、成功與失敗的判斷邏輯全部收攏到一個函式裡,呼叫端只需要提供網址與參數。

把請求設定交給一個函式

核心概念是:傳入使用者自訂的 options,函式內部補齊預設值後,再回傳一份可以直接餵給 $.ajax 的設定物件。

// 依來源自動判斷同域或跨域
var ajaxSettings = function (opt) {
  var url = opt.url;
  // 同域用 json,跨域則退回 jsonp
  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) {
      // 若後端回傳字串,先轉成物件
      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 () {
      if (opt.error) opt.error();
    }
  };
};

這段程式碼解決了三個常見問題:跨域自動切換 jsonp、預設關閉快取避免拿到舊資料,以及把「HTTP 成功但業務失敗」的情況交由同一組 callback 處理。

先約定好回傳格式

封裝能否順利,關鍵在於前後端對回傳結構有共識。實務上常見的寫法是:

// 成功
{ "code": 200, "data": [], "success": true }
// 失敗
{ "code": 200, "info": "error", "success": false }

只要 success 欄位一致,前端就能用同一套邏輯分流,不必為每個介面寫不同的判斷。

順手處理 HTML 實體

有些後端輸出會夾帶  、< 這類實體字元,直接 parseJSON 就會出錯。可以在全域設定中掛一個 converter,先還原再解析。

function unescapeEntity(str) {
  if (str === null) return '';
  str = str.toString();
  if (str.indexOf(';') < 0) return str;
  var reg = /&(?:nbsp|#160|lt|#60|gt|62|amp|#38|quot|#34);/g;
  var entity = { '&nbsp;': ' ', '&#160;': ' ', '&lt;': '<', '&#60;': '<',
                 '&gt;': '>', '&#62;': '>', '&amp;': '&', '&#38;': '&',
                 '&quot;': '"', '&#34;': '"' };
  return str.replace(reg, function (c) { return entity[c]; });
}

$.ajaxSetup({
  global: true,
  cache: false,
  converters: {
    'text json': function (response) {
      return jQuery.parseJSON(unescapeEntity(response));
    }
  }
});

全域攔截權限與錯誤

登入逾時、無權限、頁面不存在這類状况,實在不必每個請求各寫一次。用 ajaxComplete 攔下來統一處理即可。

$(document).ajaxComplete(function (evt, req) {
  if (!req || !req.responseJSON) return;
  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';
  }
});

$(document).ajaxError(function (evt, req) {
  // 200 與 0 屬於業務層級的失敗,已在 success 中處理
  if (req && (req.status === 200 || req.status === 0)) return false;
  var msg = '錯誤:';
  if (req && req.responseJSON) {
    msg += (req.responseJSON.code || '') + (req.responseJSON.info || '系統異常,請重試');
  } else {
    msg = '系統異常,請重試';
  }
  alert(msg);
});

呼叫端有多簡單

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

封裝的價值不在程式碼行數,而在於把「每個人都可能忘記的事」變成預設行為。等到要調整錯誤提示樣式、加入 loading 遮罩或統一帶上 token 時,也只需要改一個地方。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved