問題描述
我正在處理一個項目,該項目有幾個我無法更改的腳本.這些腳本通過 AJAX 更新頁面.更新完成后,我需要運行一些代碼.
I'm working on a project that has several scripts that I cannot change. These scripts update the page via AJAX. When the update is complete I need to run some code.
當任何 XMLHttpRequest 完成時是否會觸發任何事件?(或任何 XMLHttpRequest 狀態更改?).
Is there any event that fires when any XMLHttpRequest is complete? (or any XMLHttpRequest state change?).
不幸的是,我無法訪問用于發出請求的特定 XMLHttpRequest 對象.
Unfortunately I cannot access the specific XMLHttpRequest object used to make the request.
謝謝,
推薦答案
不使用 jQuery,您可以掛鉤 open
方法來為每個 XHR 對象的 readystatechange
事件附加一個監聽器在 XHR 對象被 open
ed 時.確保在發生任何 Ajax 之前運行以下代碼:
Without jQuery, you can hook the open
method to attach a listener for each XHR object's readystatechange
events at the time the XHR object is open
ed. Ensure the following code runs before any Ajax occurs:
// save the real open
var oldOpen = XMLHttpRequest.prototype.open;
function onStateChange(event) {
// fires on every readystatechange ever
// use `this` to determine which XHR object fired the change event
}
XMLHttpRequest.prototype.open = function() {
// when an XHR object is opened, add a listener for its readystatechange events
this.addEventListener("readystatechange", onStateChange)
// run the real `open`
oldOpen.apply(this, arguments);
}
或者,如果您只關心成功的 load
事件,則可以偵聽該事件而不是 readystatechange
.
Alternatively, if you only care about successful load
events, you can listener for that event instead of readystatechange
.
這篇關于當任何 XMLHttpRequest 完成時如何運行函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!