我设置了通常的 XMLHttpRequest,到目前为止一切正常,我可以检索数据和 readyState 更改并执行各种操作。
但是没有发生的一件事是 readyState 在达到 0 时会触发 onreadystatechange() 函数。
现在我想知道......为什么?
我查看了XMLHttpRequest MDN 条目,但没有提到为什么当 readyState 达到 0 时不应触发 onreadystatechange。我也没有找到关于该主题的其他信息......
片段:
// Inside a class, this = class instance
this.socket = new XMLHttpRequest();
// For easy access of this class instance in onreadystatechange
var client = this;
// Write current readyState to console
this.socket.onreadystatechange = function ()
{
// Adding this just to verify there are no errors in if block
console.log("readyState: "+client.socket.readyState);
if(client.socket.readyState === 0)
{
console.log("readyState is 0");
}
else
{
console.log("readyState is "+client.socket.readyState);
}
}
当 XMLHttpRequest 套接字处理完请求后,XMLHttpRequest 实例将具有值 readyState===0,至少 Firefox 的 JS 控制台告诉我这一点。
发出请求后,JS 控制台正确列出了 readyStates 1-4 的日志消息,但没有列出 readyState 0 的消息,不是在请求之前,也不是在请求之后。
理论上,当readyState从4变回0时,不应该触发onreadystatechange()函数吗?在 macOS 上使用当前 FF 和 Safari 以及在 Win 上使用 IE11 进行了检查,到处都是相同的行为,onreadystatechange() 永远不会为 readyState 0 触发。
XMLHttpRequest 是故意不这样做,还是我做错了什么?感谢任何有用的输入。:)
(请不要“使用 jQuery”评论或类似的评论,谢谢。)
更新:
结果表明,在成功或失败的请求完成后,readyState 将永远保持在 4,并在 FF、IE、Safari 中进行了验证。
但是,如果正在进行的请求被中止,readyState 将从 > 0 返回到 0。所以一个 readystatechange 确实发生了,但是 onreadystatechange 没有被触发,在 FF 和 Safari 中验证了这一点。
更新 3:
根据XMLHttpRequest 规范,当 XHR 处于 readyState 3(接收)并被中止时,XHR 应该使用 onreadystatechange 事件将 readyState 设置为 4(完成),发出网络错误,然后在没有onreadystatechange 事件的情况下将 readyState 设置为 0(未发送) .
但是当我中止处于 readyState 3(接收)的 XHR 时,它首先会使用 onreadystatechange 事件和 HTTP 状态 200(OK)将 readyState 设置为 4(完成),然后它会触发 onabort 和 onloadend 并将 readyState 重置为 0( unsent) ...但绝不会触发 onerror 事件。
非常混乱。