我可以保证 onreadystatechange 最终总是会在 readState == 4 的情况下被调用吗?
我在嵌入式设备上使用 XMLHttpRequest,该设备为 API 提供非标准扩展,以允许在请求完成后手动清理资源。
我是否可以假设,对于所有情况(成功或其他情况,例如 404、DNS 查找失败等),对 send() 方法的调用最终将导致我的 onreadstatechange 处理程序被调用,并且 readstate == 4 ?
或者,换句话说,假设此实现的 XHR 在所有其他方面的行为与标准浏览器的行为类似,那么以下代码是否总是会导致调用 destroy() 方法?
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
callback(xhr.responseText);
if (xhr.destroy) { // must call this to prevent memory leak
xhr.destroy();
}
}
};
xhr.open(method, url, true);
xhr.send(null);
I'm using XMLHttpRequest on an embedded device that provides a non-standard extension to the API to allow manual cleanup of resources after the request has finished.
Can I assume that, for all cases (successful or otherwise, eg 404, DNS lookup failed, etc), a call to the send() method will eventually result in my onreadstatechange handler being called with readyState == 4?
Or, to put it another way, assuming that this implementation's XHR behaves similarly to that of the standard browsers in all other ways, will the following code always result in the destroy() method being called?
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
callback(xhr.responseText);
if (xhr.destroy) { // must call this to prevent memory leak
xhr.destroy();
}
}
};
xhr.open(method, url, true);
xhr.send(null);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不会。
在某些情况下,例如当调用
abort()
时,状态可能会在UNSENT
处终止 (3.6.5)。即使在“正常”操作期间,如果发生错误并引发异常,则状态可能会在
DONE
之外的其他位置终止。请阅读规范中有关状态的部分了解更多信息。
No.
In some cases, for example when calling
abort()
, the state may terminate atUNSENT
(3.6.5).Even during "normal" operation, if an error occurs and an exception is thrown, then the state may terminate at something other than
DONE
.Read the spec's section on states for more information.