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

时间:2021-11-24 03:35:49

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,

谢谢,

1 个解决方案

#1


15  

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 opened. Ensure the following code runs before any Ajax occurs:

没有jQuery,您可以挂起open方法,以便在打开XHR对象时为每个XHR对象的readystatechange事件附加一个侦听器。确保在出现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 load events, you can listener for that event instead of readystatechange.

另外,如果您只关心成功的加载事件,您可以侦听该事件,而不是readystatechange。

#1


15  

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 opened. Ensure the following code runs before any Ajax occurs:

没有jQuery,您可以挂起open方法,以便在打开XHR对象时为每个XHR对象的readystatechange事件附加一个侦听器。确保在出现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 load events, you can listener for that event instead of readystatechange.

另外,如果您只关心成功的加载事件,您可以侦听该事件,而不是readystatechange。