如何运行函数时任XMLHtt prequest完成? [英] How to run a function when any XMLHttpRequest is complete?
问题描述
我的工作,有一些脚本,我不能改变的项目。这些脚本通过AJAX更新页面。当更新完成后,我需要运行一些code。
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.
有没有事件触发时任XMLHtt prequest完成? (或任何XMLHtt prequest状态的改变?)。
Is there any event that fires when any XMLHttpRequest is complete? (or any XMLHttpRequest state change?).
不幸的是,我不能访问用于使该请求的特定XMLHtt prequest对象。
Unfortunately I cannot access the specific XMLHttpRequest object used to make the request.
谢谢
推荐答案
如果没有的jQuery,你可以连接的打开
方法附加一个监听器为每个XHR对象的 readystatechange
事件在当时XHR对象是打开
编辑。确保以下code运行任何阿贾克斯发生之前:
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);
}
另外,如果你只关心成功的负荷
事件,可以侦听器的事件,而不是 readystatechange
。
Alternatively, if you only care about successful load
events, you can listener for that event instead of readystatechange
.
这篇关于如何运行函数时任XMLHtt prequest完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!