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


当前回答

您可以使用以下命令中止任何连续的ajax调用

<input id="searchbox" name="searchbox" type="text" />

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
     var request = null;
        $('#searchbox').keyup(function () {
            var id = $(this).val();
            request = $.ajax({
                type: "POST", //TODO: Must be changed to POST
                url: "index.php",
                data: {'id':id},
                success: function () {
    
                },
                beforeSend: function () {
                    if (request !== null) {
                        request.abort();
                    }
                }
            });
        });
</script>

其他回答

正如线程中的许多人所指出的,仅仅因为请求在客户端被中止,服务器仍然会处理该请求。这会在服务器上产生不必要的负载,因为它正在做我们已经停止在前端侦听的工作。

我试图解决的问题(其他人可能也会遇到)是,当用户在输入字段中输入信息时,我想发出一个请求,请求使用Google Instant类型的感觉。

为了避免发出不必要的请求并保持前端的快速性,我执行了以下操作:

var xhrQueue = [];
var xhrCount = 0;

$('#search_q').keyup(function(){

    xhrQueue.push(xhrCount);

    setTimeout(function(){

        xhrCount = ++xhrCount;

        if (xhrCount === xhrQueue.length) {
            // Fire Your XHR //
        }

    }, 150);

});

这将基本上每150毫秒发送一个请求(您可以根据自己的需要定制一个变量)。如果您无法理解这里到底发生了什么,请在If块之前将xhrCount和xhrQueue记录到控制台。

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

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

我已经分享了一个演示,演示了如何取消AJAX请求——如果在预定义的等待时间内没有从服务器返回数据。

HTML格式:

<div id="info"></div>

JS代码:

var isDataReceived= false, waitTime= 1000; 
$(function() {
    // Ajax request sent.
     var xhr= $.ajax({
      url: 'http://api.joind.in/v2.1/talks/10889',
      data: {
         format: 'json'
      },     
      dataType: 'jsonp',
      success: function(data) {      
        isDataReceived= true;
        $('#info').text(data.talks[0].talk_title);        
      },
      type: 'GET'
   });
   // Cancel ajax request if data is not loaded within 1sec.
   setTimeout(function(){
     if(!isDataReceived)
     xhr.abort();     
   },waitTime);   
});

这是一个异步请求,意味着一旦它被发送,它就在那里。

如果您的服务器由于AJAX请求而启动了一个非常昂贵的操作,那么您所能做的最好就是打开服务器以侦听取消请求,然后发送一个单独的AJAX请求,通知服务器停止它正在做的任何事情。

否则,只需忽略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演示