XMLHttpRequest 的 onerror 处理程序应该何时触发

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

问题描述

限时送ChatGPT账号..

我在理解 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)

另外,我想知道这是否意味着 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 处理程序应该何时触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

SCRIPT5: Access is denied in IE9 on xmlhttprequest(SCRIPT5:在 IE9 中对 xmlhttprequest 的访问被拒绝)
XMLHttpRequest module not defined/found(XMLHttpRequest 模块未定义/未找到)
Show a progress bar for downloading files using XHR2/AJAX(显示使用 XHR2/AJAX 下载文件的进度条)
How can I open a JSON file in JavaScript without jQuery?(如何在没有 jQuery 的情况下在 JavaScript 中打开 JSON 文件?)
How do I get the HTTP status code with jQuery?(如何使用 jQuery 获取 HTTP 状态码?)
quot;Origin null is not allowed by Access-Control-Allow-Originquot; in Chrome. Why?(“Access-Control-Allow-Origin 不允许 Origin null在铬.为什么?)