改写答案:see original answer in revision history
您可以覆盖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)
{
// your oncomplete function here
this.onreadystatechange = handler;
}
};
xhrSend.apply(this, arguments);
};
})();
编辑:以上函数不使用jQuery的要求工作,所以可能它可能不会与其他库也是如此。下面的修订版解决了setTimeout
黑客延迟覆盖处理程序的代码的问题。当然,使用jQuery,您可以使用全局处理程序,但对于具有类似行为的其他库,这将会很有用。
(function() {
function globalHandler() {
if (this.readyState == 4) {
// your oncomplete code here
}
}
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);
};
})();
http://jsfiddle.net/gilly3/FuacA/5/
我在IE7-9进行了测试,Chrome浏览器的最新版本和FF
我也尝试过。仍然没有效果。问题是我的ajax请求不是通过jQuery完成的吗? – iandisme
@iandisme - YES !!绝对!那是你的问题。 '.ajaxSuccess'是一个* jQuery事件*。如果您在jQuery之外制作常规的XMLHttpRequest,jQuery无法了解它。 – gilly3
@iandisme - 查看我的非jQuery解决方案的更新答案。 – gilly3