方法一
// TODO 主要功能為重寫ajax $.ajaxSetup({ cache: false, headers: { "xxxxx": "xxxxx" }, beforeSend: function (XMLHttpRequest) { }, complete: function (XMLHttpRequest, textStatus) { }, error: function (xhr, textStatus, errorThrown) { } });
方法二
(function($) {
// 首先備份下jquery的ajax方法
var _ajax = $.ajax; // 重寫jquery的ajax方法 $.ajax = function(options) { // 備份opt中error和success方法 var callback = { "beforeSend" : function(XHR) { }, "complete" : function(XHR, TS) { }, "error" : function(XMLHttpRequest, textStatus, errorThrown) { }, "success" : function(data, textStatus) { } } // 判斷參數中是否有beforeSend回調函數 if (options.beforeSend) { callback.beforeSend = options.beforeSend; } // 判斷參數中是否有complete回調函數 if (options.complete) { callback.complete = options.complete; } // 判斷參數中是否有error回調函數 if (options.error) { callback.error = options.error; } // 判斷參數中是否有success回調函數 if (options.success) { callback.success = options.success; } // 擴展增強處理 var _opt = $.extend(options, { error : function(XMLHttpRequest, textStatus, errorThrown) { // 錯誤方法增強處理 callback.error(XMLHttpRequest, textStatus, errorThrown); }, success : function(data, textStatus) { // 成功回調方法增強處理 callback.success(data, textStatus); }, beforeSend : function(XHR) { // 提交前回調方法 callback.beforeSend(XHR); }, complete : function(XHR, TS) { // 請求完成后回調函數 (請求成功或失敗之后均調用)。 callback.complete(XHR, TS); } }); // 返回重寫的ajax return _ajax(_opt); }; })(jQuery);