你想要完成的事情无法完成ajaxSend
。问题是ajaxSend
显然可以使用原件的副本xhr
and 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()
or .load()
) 内部使用$.ajax
,所以这应该适用于通过 jQuery 完成的每个 AJAX 请求(不过我还没有测试过......)。
Something like that should also work with "pure" JavaScript by hacking the
XMLHttpRequest.prototype
. Note that the following won't work in IE, which uses
ActiveXObject
instead of
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();