重写后的回答: 查看修订历史中的原始回答
您可以通过覆盖默认的XMLHttpRequest
的send
方法,并劫持readystatechange
处理程序来实现:
(function ()
{
var xhrSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function ()
{
var handler = this.onreadystatechange;
this.onreadystatechange = function ()
{
if (handler) {
if (handler.handleEvent) handler.handleEvent.apply(xhr, arguments);
else handler.apply(xhr, arguments);
}
if (this.readyState == 4)
{
this.onreadystatechange = handler;
}
};
xhrSend.apply(this, arguments);
};
})();
编辑:上面的函数不能与jQuery请求一起使用,因此可能也会在其他库中失败。下面的修订通过使用setTimeout
技巧来延迟覆盖处理程序的代码来解决了这个问题。当然,对于jQuery,您可以使用.ajaxSuccess()
全局处理程序,但对于具有类似行为的其他库,这将非常有用。
(function() {
function globalHandler() {
if (this.readyState == 4) {
}
}
var xhrSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function() {
var xhr = this;
if (xhr.addEventListener) {
xhr.removeEventListener("readystatechange", globalHandler);
xhr.addEventListener("readystatechange", globalHandler, false);
}
else {
function readyStateChange() {
if (handler) {
if (handler.handleEvent)
handler.handleEvent.apply(xhr, arguments);
else
handler.apply(xhr, arguments);
}
globalHandler.apply(xhr, arguments);
setReadyStateChange();
}
function setReadyStateChange() {
setTimeout(function() {
if (xhr.onreadystatechange != readyStateChange) {
handler = xhr.onreadystatechange;
xhr.onreadystatechange = readyStateChange;
}
}, 1);
}
var handler;
setReadyStateChange();
}
xhrSend.apply(xhr, arguments);
};
})();
点击链接,这是一个测试代码,我已经在IE7-9、Chrome和FF最新版本中进行了测试。
.ajaxSuccess
是一个jQuery事件。如果你在jQuery之外进行常规的XMLHttpRequest,那么jQuery就无法知道它。 - gilly3.handleEvent
部分,我将接受您的答案并授予悬赏。这样其他人也可以从您的帮助中受益。 - iandisme