是否可以使用jQuery取消/中止尚未收到响应的Ajax请求?


当前回答

AJAX请求可能无法按启动顺序完成。您可以选择忽略除最新的AJAX响应之外的所有AJAX响应,而不是放弃:

创建计数器启动AJAX请求时增加计数器使用计数器的当前值“标记”请求在成功回调中,将标记与计数器进行比较,以检查它是否是最近的请求

代码大纲:

var xhrCount = 0;
function sendXHR() {
    // sequence number for the current invocation of function
    var seqNumber = ++xhrCount;
    $.post("/echo/json/", { delay: Math.floor(Math.random() * 5) }, function() {
        // this works because of the way closures work
        if (seqNumber === xhrCount) {
            console.log("Process the response");
        } else {
            console.log("Ignore the response");
        }
    });
}
sendXHR();
sendXHR();
sendXHR();
// AJAX requests complete in any order but only the last 
// one will trigger "Process the response" message

jsFiddle演示

其他回答

您不能撤回请求,但可以设置超时值,超过该值后将忽略响应。有关jquery AJAX选项,请参阅本页。我相信如果超过超时时间,将调用错误回调。每个AJAX请求都有一个默认超时。

您也可以对请求对象使用abort()方法,但是,虽然它会导致客户端停止侦听事件,但它可能不会阻止服务器处理它。

如果xhr.art();导致页面重新加载,

然后,您可以在中止前设置onreadystatechange以防止:

// ↓ prevent page reload by abort()
xhr.onreadystatechange = null;
// ↓ may cause page reload
xhr.abort();

无论是jquery ajax对象还是本机XMLHTTPRequest对象,只需调用xhr.abourt()。

例子:

//jQuery ajax
$(document).ready(function(){
    var xhr = $.get('/server');
    setTimeout(function(){xhr.abort();}, 2000);
});

//native XMLHTTPRequest
var xhr = new XMLHttpRequest();
xhr.open('GET','/server',true);
xhr.send();
setTimeout(function(){xhr.abort();}, 2000);

AJAX请求可能无法按启动顺序完成。您可以选择忽略除最新的AJAX响应之外的所有AJAX响应,而不是放弃:

创建计数器启动AJAX请求时增加计数器使用计数器的当前值“标记”请求在成功回调中,将标记与计数器进行比较,以检查它是否是最近的请求

代码大纲:

var xhrCount = 0;
function sendXHR() {
    // sequence number for the current invocation of function
    var seqNumber = ++xhrCount;
    $.post("/echo/json/", { delay: Math.floor(Math.random() * 5) }, function() {
        // this works because of the way closures work
        if (seqNumber === xhrCount) {
            console.log("Process the response");
        } else {
            console.log("Ignore the response");
        }
    });
}
sendXHR();
sendXHR();
sendXHR();
// AJAX requests complete in any order but only the last 
// one will trigger "Process the response" message

jsFiddle演示

我正在进行实时搜索解决方案,需要取消可能比最新/最新请求花费更长时间的未决请求。

在我的案例中,我使用了这样的方法:

//On document ready
var ajax_inprocess = false;

$(document).ajaxStart(function() {
ajax_inprocess = true;
});

$(document).ajaxStop(function() {
ajax_inprocess = false;
});

//Snippet from live search function
if (ajax_inprocess == true)
{
    request.abort();
}
//Call for new request