你试图完成的事情不能用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()
或.load()
)在内部使用$.ajax
,所以这应该适用于通过 jQuery 完成的每个 AJAX 请求(虽然我还没有测试过......)。
通过破解
XMLHttpRequest.prototype
. 请注意,以下内容在 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();