这几乎总是正确的。但是,一个重大区别是,在通常触发onreadystatechange
事件处理程序readyState==4
的情况下onerror
(通常是网络连接问题),也会触发事件处理程序。在这种情况下,其状态为0。我已经验证了这种情况会在最新的Chrome,Firefox和IE上发生。
因此,如果您正在使用onerror
并且针对现代浏览器,则不应使用onreadystatechange
而是应该使用onload
,这似乎可以保证仅在HTTP请求成功完成(带有真实的响应和状态代码)时才被调用。否则,您可能最终会在发生错误的情况下触发两个事件处理程序(这是我从经验上发现这种特殊情况的方式。)
这是我编写的Plunker测试程序的链接,该程序可让您测试不同的URL,并查看事件和readyState
值的实际顺序,如JavaScript应用在不同情况下所见。JS代码也在下面列出:
var xhr;
function test(url) {
xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function() { log(xhr, "readystatechange") });
xhr.addEventListener("loadstart", function(ev) { log(xhr, "loadstart", ev.loaded + " of " + ev.total) });
xhr.addEventListener("progress", function(ev) { log(xhr, "progress", ev.loaded + " of " + ev.total) });
xhr.addEventListener("abort", function() { log(xhr, "abort") });
xhr.addEventListener("error", function() { log(xhr, "error") });
xhr.addEventListener("load", function() { log(xhr, "load") });
xhr.addEventListener("timeout", function(ev) { log(xhr, "timeout", ev.loaded + " of " + ev.total) });
xhr.addEventListener("loadend", function(ev) { log(xhr, "loadend", ev.loaded + " of " + ev.total) });
xhr.open("GET", url);
xhr.send();
}
function clearLog() {
document.getElementById('log').innerHTML = '';
}
function logText(msg) {
document.getElementById('log').innerHTML += msg + "<br/>";
}
function log(xhr, evType, info) {
var evInfo = evType;
if (info)
evInfo += " - " + info ;
evInfo += " - readyState: " + xhr.readyState + ", status: " + xhr.status;
logText(evInfo);
}
function selected(radio) {
document.getElementById('url').value = radio.value;
}
function testUrl() {
clearLog();
var url = document.getElementById('url').value;
if (!url)
logText("Please select or type a URL");
else {
logText("++ Testing URL: " + url);
test(url);
}
}
function abort() {
xhr.abort();
}