[英]Modify ajax response before any bound callbacks get executed
問題
我需要一種在觸發所有綁定的回調之前修改應用程序中所有ajax響應的方法。
解
標准ajax事件,無論是全局的還是本地的,都無法在觸發應用綁定回調之前提供一種修改響應的好方法。
觸發ajax事件的順序是jquery的ajax事件文檔中指出的順序,即
注意,從服務器返回響應之后,但在運行成功/ erorr回調之前,沒有執行任何鈎子,例如,在ajaxSend
之后但在success|error
之前運行的一種ajaxReturn
我的破解方法是使用$ .ajaxPrefilter在ajaxStart
之前執行, ajaxStart
已經綁定的成功/錯誤回調包裝在另一個函數中,這將允許我修改options
對象,從而修改返回的數據。
以下是執行包裝的實用程序功能和示例:
var alterResponse = function (opts) {
var callback = function (options, originalOptions, jqXHR) {
if (options.url.match(opts.urlMatch)) {
// Cache original callback.
var originalSuccess = originalOptions.success || options.success;
originalOptions.success = options.success = function () {
// Call wrapper that will modify the response object.
opts.successWrapper.call(null, options, originalOptions, jqXHR, originalSuccess);
};
}
};
if (opts.dataTypes) {
$.ajaxPrefilter(opts.dataTypes, callback)
}
else {
$.ajaxPrefilter(callback);
}
};
alterResponse({
urlMatch: /myurl/g, // Filter urls you what to tamper with.
successWrapper: function (options, originalOptions, jqXHR, originalFn) {
options.data.customVar = 'customValue';
originalFn(options, originalOptions, jqXHR);
}
});
我不得不提到我將其用於測試目的,因此我不關心性能,內存和開銷。
如果要在服務器到達事件處理程序之前修改從服務器返回的數據,請使用dataFilter:
jquery.ajaxSetup({
dataFilter: function (data, type) {
//modify your data here
return data;
}
});
您可以使用任何全局ajax事件
$(document).ajaxSuccess(function() {
alert("An individual AJAX call has completed successfully");
});
//or...
$(document).ajaxComplete(function() {
alert("ALL current AJAX calls have completed");
});
//or..
$(function() {
$.ajaxSetup({
complete: function(xhr, textStatus) {
// will be raised whenever an AJAX request completes (success or failure)
},
success: function(result) {
// will be raised whenever an AJAX request succeeds
},
etc ... you could use any available option
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.