問題描述
我在理解 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 處理程序應該何時觸發的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!