我正在处理一个项目,该项目有几个我无法更改的脚本.这些脚本通过 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模板网!