When should XMLHttpRequest#39;s onerror handler fire(XMLHttpRequest 的 onerror 处理程序应该何时触发)
问题描述
我在理解 XMLHttpRequest
的处理程序时有点问题.规范说明了 onerror
处理程序:
I have a little problem understanding XMLHttpRequest
's handlers. The specification says this about the onerror
handler:
error
[Dispatched ... ] 请求失败时.
error
[Dispatched ... ] When the request has failed.
load
[Dispatched ... ] 当请求成功完成时.
load
[Dispatched ... ] When the request has successfully completed.
问题是,请求失败"是什么意思.那可能是
The problem is, what does it mean that "the request has failed". That could be
- 根本无法发出请求(例如,连接被拒绝和此类错误),或者
- 上面加上服务器返回了一个错误代码(例如404)
另外,我想知道这是否意味着 onerror
和 onload
不应该同时触发.
Also, I'd like to know whether it means onerror
and onload
should never fire simultaneously.
此引用 表示应该执行 onerror
处理程序取决于 status
代码和 onload
取决于 readyState
.这表明它们并不相互排斥,但是,我认为这不是权威信息.
This reference indicates the onerror
handler should be executed depending on the status
code and onload
depending on readyState
. That would indicate they are not mutually exclusive, however, I don't think this is an authoritative information.
我问是因为使用最新的 Opera 快照,我发现即使在 404 状态码上也会触发 onload
.我知道测试 status
是肯定的,但我想知道这是我必须按照规范执行的操作,还是只是解决 Opera 中的错误的一种解决方法.
I'm asking because using the latest Opera snapshot, I found onload
is fired even on 404 status code. I know testing status
is a sure bet, but I'd like to know whether it's something I have to do per specification or just a workaround for a bug in Opera.
推荐答案
正如评论中提到的,onerror
在网络级别出现故障时触发.如果错误仅存在于应用程序级别,例如,发送了 HTTP 错误代码,则 onload
仍然会触发.您需要在 onreadystatechange
处理程序中显式测试返回的状态代码.
As mentioned in the comments, onerror
fires when there is a failure on the network level. If the error only exists on the application level, e.g., an HTTP error code is sent, then onload
still fires. You need to test the returned status code explicitly in your onreadystatechange
handler.
请注意,被拒绝的跨域请求也会触发 onerror
处理程序.
Note that a denied cross-domain request will also fire the onerror
handler.
这篇关于XMLHttpRequest 的 onerror 处理程序应该何时触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:XMLHttpRequest 的 onerror 处理程序应该何时触发


基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01