简体   繁体   English

如何检查 ajax 请求是否被浏览器中止

[英]How to check if ajax request was aborted by browser

I'm making long polling ajax requests to my server我正在向我的服务器发出长轮询 ajax 请求

$.ajax({
    url: "someurl.com", 
    success: function(resp) { ... },
    error: function() { ... }
});

but if there is some inte.net connection problems for a short period of time Firefox 10 aborts the request and hence my script doesn't receive response from the server (in older versions of FF there were no such request aborting).但是如果在短时间内出现一些 inte.net 连接问题 Firefox 10 中止请求,因此我的脚本没有收到来自服务器的响应(在旧版本的 FF 中没有这样的请求中止)。

How can I found out that my ajax request was aborted by browser?我怎么知道我的 ajax 请求被浏览器中止了? Maybe there are some event for it?也许有一些事件? Or can I force browser not to abort my ajax requests if the.network connection is down?或者,如果 .network 连接断开,我可以强制浏览器不中止我的 ajax 请求吗?

For XMLHTTPRequest, it gives status "0" saying that request not initialized . 对于XMLHTTPRequest,它给出状态"0"表示request not initialized You can catch that status and know that req has been aborted. 您可以捕获该状态并知道req已被中止。

Perhaps you could add a timeout to the call? 也许您可以在通话中添加超时?

  $.ajax({
        url: "test.html",
        error: function(){
            // will fire when timeout is reached
        },
        success: function(){
            //do something
        },
        timeout: 3000 // sets timeout to 3 seconds
    });

Check the abort status of the jqXHR in the.fail (previously.error) function.在.fail (previously.error) function中检查jqXHR的中止状态。

let request = $.ajax({
    // your options
})

request.fail(jqXHR,textStatus){
    if(jqXHR.abort){
        alert("Aborted")
    }else{
        alert("Other error")
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM