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

How to run a function when any XMLHttpRequest is complete?(当任何 XMLHttpRequest 完成时如何运行函数?)
本文介绍了当任何 XMLHttpRequest 完成时如何运行函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个项目,该项目有几个我无法更改的脚本.这些脚本通过 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 对象被 opened 时.确保在发生任何 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 opened. 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 完成时如何运行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)