改寫答案: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