如何捕获 XMLHttpRequest 的所有终止
我有一个条件,必须在 XMLHttpRequest 使用之前和之后保持,但在使用期间则不然。示例:
var running = false; // condition
function go (callback)
{
running = true; // condition broken
var http = new XMLHttpRequest ();
http .open ("GET", url, true);
http .onreadystatechange = function ()
{
if (4 == this .readyState)
{
try
{
callback (this .responseText);
}
catch (e) {}
running = false; // condition restored
}
}
}
我需要保证 running
最终始终会变为 false
,无论 XMLHttpRequest
如何执行。
这是否足够,还是我需要检查其他一些可能发生的情况?
I have an condition which has to hold before and after an XMLHttpRequest usage, but not during. Example:
var running = false; // condition
function go (callback)
{
running = true; // condition broken
var http = new XMLHttpRequest ();
http .open ("GET", url, true);
http .onreadystatechange = function ()
{
if (4 == this .readyState)
{
try
{
callback (this .responseText);
}
catch (e) {}
running = false; // condition restored
}
}
}
I need to guarantee that running
will always eventually become false
, regardless of how the XMLHttpRequest
plays out.
Is this sufficient or do I need to check some other eventualities?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来这个检查就足够了(http://www.w3.org/TR/XMLHttpRequest/)。如果数据传输已完成或传输过程中出现问题,readyState 为 4。
确保为超时设置一些合理的值(默认为 0,即没有超时)。
It looks like that this check is enough (http://www.w3.org/TR/XMLHttpRequest/). readyState is 4 if the data transfer has been completed or something went wrong during the transfer.
Make sure you set some reasonable value for timeout (the default is 0, that is no timeout).