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 完成时如何运行函数?


基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01