javascript 当任何 XMLHttpRequest 完成时如何运行函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18259301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:14:52  来源:igfitidea点击:

How to run a function when any XMLHttpRequest is complete?

javascriptjqueryajaxxmlhttprequest

提问by MCM

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.

我正在处理一个项目,该项目有几个我无法更改的脚本。这些脚本通过 AJAX 更新页面。更新完成后,我需要运行一些代码。

Is there any event that fires when any XMLHttpRequest is complete? (or any XMLHttpRequest state change?).

当任何 XMLHttpRequest 完成时,是否会触发任何事件?(或任何 XMLHttpRequest 状态更改?)。

Unfortunately I cannot access the specific XMLHttpRequest object used to make the request.

不幸的是,我无法访问用于发出请求的特定 XMLHttpRequest 对象。

Thanks,

谢谢,

回答by apsillers

Without jQuery, you can hook the openmethod to attach a listener for each XHR object's readystatechangeevents at the time the XHR object is opened. Ensure the following code runs before any Ajax occurs:

如果没有 jQuery,您可以挂钩该open方法,以便readystatechangeopen编辑XHR 对象时为每个 XHR 对象的事件附加一个侦听器。确保在任何 Ajax 发生之前运行以下代码:

// 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);
}

Alternatively, if you only care about successful loadevents, you can listener for that event instead of readystatechange.

或者,如果您只关心成功的load事件,则可以侦听该事件而不是readystatechange.