本文介绍了XMLHttpRequest 的 onerror 处理程序应该何时触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解 XMLHttpRequest 的处理程序时有点问题.规范说明了 onerror 处理程序:

I have a little problem understanding XMLHttpRequest's handlers. The specification says this about the onerror handler:

error [Dispatched ... ] 请求失败时.

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)

另外,我想知道这是否意味着 onerroronload 不应该同时触发.

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 处理程序应该何时触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 23:22