Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/429.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript XMLHttpRequest超时情况-onreadystatechange在ontimeout之前执行?_Javascript_Xmlhttprequest - Fatal编程技术网

Javascript XMLHttpRequest超时情况-onreadystatechange在ontimeout之前执行?

Javascript XMLHttpRequest超时情况-onreadystatechange在ontimeout之前执行?,javascript,xmlhttprequest,Javascript,Xmlhttprequest,我正在使用XMLHttpRequest发出异步GET请求。我有 xhr.onreadystatechange = function () { if (xhr.readyState === 4) {//Handle only if the state has completed if (xhr.status === 200) { successHandler.call(context, xhr.responseText); } els

我正在使用XMLHttpRequest发出异步GET请求。我有

xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {//Handle only if the state has completed
        if (xhr.status === 200) {
            successHandler.call(context, xhr.responseText);
        } else {
            console.warn('onreadystatechange:' + new Date().getTime());
            failureHandler.call(context, xhr.status, xhr.statusText);
        }
    }
};
xhr.ontimeout = function () {
    console.warn('ontimeout: ' + new Date().getTime());
    failureHandler.call(context, 0, 'timeout');
};

我正在使用网络限制强制超时。我观察到,
onreadystatechange
ontimeout
在超时情况下调用回调,
onreadystatechange
前面的
ontimeout
。我的印象是,两人中只有一人会被处决。我用的是铬。有人知道这是否是预期的吗?

现代解决方案是使用适当的XMLHttpRequest事件:如果要单独处理这些情况,则使用onload和onerror;如果希望检测HTTP请求完成而不管成功与否,则使用onloadend;如果要超时,则使用ontimeout。发生超时时,会调用ontimeout,但不会调用onloadend。onreadystatechange看起来最好安静地死去。可在此处找到完整的事件集:

自从onreadystatechange→ontimeout序列似乎不会影响IE 8,出于我的目的,我很乐意做以下事情:在IE 8中使用onreadystatechange,在Firefox/modern MSIE中使用onloadend(使用以下测试查看事件是否定义:if(“onloadend”在httpObj中)…)


这是一个内部系统,所以这对我来说就足够了;对于OP,可能需要更多的测试。

onreadystatechangeontimeout之前被调用,为了解决这个问题,我使用了setTimeout和一些指示调用了ontimeout的东西,我决定如下:

xhr.onreadystatechange = function (){
    if (xhr.status == 0){
        return setTimeout(()=>{
           if (xhr['istimeout']) return

           onResponse({status:xhr.status, statusText:xhr.statusText})
        }, 1)
    }
}

xhr.ontimeout = function handleTimeout() {
     xhr['istimeout'] = true
     onResponse({
         status: xhr.status,
         statusText: `timeout of xxxms exceeded`,
     })
}

为什么你觉得这是独家活动?我对
ontimeout
一无所知,但是如果
readyState
发生更改(无论是由于超时、完成还是错误),我希望调用
onreadystatechange
方法。
XMLHttpRequest
跟踪其
readyState
,超时肯定会改变它。readyState更改为值4,即
DONE
状态。我们如何知道ajax是否确实失败了,因为即使是
statusText
也是空的?@我不相信如果在从服务器接收代码之前发生超时,您可以依赖xhr.status=0:虽然这段代码可以回答这个问题,提供关于此代码为什么和/或如何回答此问题的附加上下文可提高其长期价值。