简体   繁体   English

如何取消待处理的Jquery Ajax调用?

[英]How to cancel pending Jquery Ajax call?

I have REST webservices that supports long polling. 我有支持长轮询的REST Web服务。 if server has any new data it'll send to me, if I made Jquery Ajax request. 如果服务器有任何新数据,它将发送给我,如果我提出了Jquery Ajax请求。 If there is no update from server, the request will be in pending state. 如果没有来自服务器的更新,则请求将处于挂起状态。 Now I want to cancel that request if user log out suddenly. 现在,如果用户突然注销,我想取消该请求。 I tried like 我试过像

var request=$.ajax({
--------
-
-------
});

request.abort();

But I am getting error here, since request didn't received any data from server (cause still in pending state). 但是我在这里遇到错误,因为请求没有收到来自服务器的任何数据(因为仍然处于待处理状态)。 So it is 'null'. 所以它是“空”。

How can I cancel that Ajax request ? 如何取消该Ajax请求?

Abort is regarded as an error by jquery, so you'll need to check your jqXHR's statusText in the fail handler to see if it has been aborted and handle accordingly. jQuery将Abort视为错误,因此您需要在故障处理程序中检查jqXHR的statusText,以查看其是否已中止并进行相应的处理。

Here's code to illustrate: 以下代码说明:

var jqXHR = $.ajax({
    url: '...'
});

// jqXHR.abort() is regarded as an error, so your logic for detecting
// it should go in the fail handler.  Here's how you could set this up:
jqXHR.fail(function(args) {
    if (jqXHR.statusText == 'abort') {
        console.log('AJAX aborted');
        return;
    }

    // Other error processing goes here.

});

// If pending, abort AJAX call
if (jqXHR.state() == 'pending') {
    jqXHR.abort();
}

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

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