How to run a function when any XMLHttpRequest is complete?(当任何 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 对象被 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 完成时如何运行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当任何 XMLHttpRequest 完成时如何运行函数?


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01