你要完成什麼不能ajaxSend
來完成。問題是,ajaxSend
顯然與原始的xhr
和options
對象的副本一起使用,所以這些修改不會產生任何影響。您可以輕鬆地用下面的代碼測試:
$(document).ajaxSend(function(event, xhr, options){
delete options.success;
console.log(options.success); // undefined
});
$.ajax({
url: "test.html",
success: function() { console.log("this will be printed nevertheless"); }
});
所以你不能使用ajaxSend
覆蓋成功回調。相反,你將不得不「黑客」 jQuery的AJAX功能:
// closure to prevent global access to this stuff
(function(){
// creates a new callback function that also executes the original callback
var SuccessCallback = function(origCallback){
return function(data, textStatus, jqXHR) {
console.log("start");
if (typeof origCallback === "function") {
origCallback(data, textStatus, jqXHR);
}
console.log("end");
};
};
// store the original AJAX function in a variable before overwriting it
var jqAjax = $.ajax;
$.ajax = function(settings){
// override the callback function, then execute the original AJAX function
settings.success = new SuccessCallback(settings.success);
jqAjax(settings);
};
})();
現在,你可以簡單地使用$.ajax
像往常一樣:
$.ajax({
url: "test.html",
success: function() {
console.log("will be printed between 'start' and 'end'");
}
});
據我所知,任何的jQuery的AJAX功能(如$.get()
或)在內部使用$.ajax
,所以這應該適用於通過jQuery完成的每個AJAX請求(我還沒有測試過這個,儘管...)。
類似的東西也應該用「純」的JavaScript由黑客
XMLHttpRequest.prototype
工作。請注意,以下內容在IE中不起作用,IE使用
ActiveXObject
而不是
XMLHttpRequest
。
(function(){
// overwrite the "send" method, but keep the original implementation in a variable
var origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(data){
// check if onreadystatechange property is set (which is used for callbacks)
if (typeof this.onreadystatechange === "function") {
// overwrite callback function
var origOnreadystatechange = this.onreadystatechange;
this.onreadystatechange = function(){
if (this.readyState === 4) {
console.log("start");
}
origOnreadystatechange();
if (this.readyState === 4) {
console.log("end");
}
};
}
// execute the original "send" method
origSend.call(this, data);
};
})();
使用(就像一個平常的XMLHttpRequest):
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.html", true);
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
console.log("will be printed between 'start' and 'end'");
}
};
xhr.send();
相關:http://stackoverflow.com/questions/293668/jquery-ajax-prevent-callback-from-running – pimvdb 2012-08-17 10:31:32
感謝,但它不回答我的問題,在瀏覽器獲取HTTP響應後,ajaxComplete觸發,我詢問有關在HTTP請求之前觸發的ajaxSend – ciochPep 2012-08-17 10:39:38
您是對的。我只是指出回答說必須運行回調,而且你不能阻止回調。當然,這不完全是你的問題;我也對解決方案感興趣。 – pimvdb 2012-08-17 10:42:20