Abort Ajax requests using jQuery

2018-12-30 23:24发布

Using jQuery, how can I cancel/abort an Ajax request that I have not yet received the response from?

18条回答
回忆,回不去的记忆
2楼-- · 2018-12-30 23:48

Just call xhr.abort() whether it's jquery ajax object or native XMLHTTPRequest object.

example:

//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);
查看更多
零度萤火
3楼-- · 2018-12-30 23:48

I have shared a demo that demonstrates how to cancel an AJAX request-- if data is not returned from the server within a predefined wait time.

HTML :

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

JS CODE:

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);   
});
查看更多
刘海飞了
4楼-- · 2018-12-30 23:48

If xhr.abort(); causes page reload,

Then you can set onreadystatechange before abort to prevent:

// ↓ prevent page reload by abort()
xhr.onreadystatechange = null;
// ↓ may cause page reload
xhr.abort();
查看更多
余欢
5楼-- · 2018-12-30 23:49

Just use ajax.abort() for example you could abort any pending ajax request before sending another one like this

//check for existing ajax request
if(ajax){ 
 ajax.abort();
 }
//then you make another ajax request
$.ajax(
 //your code here
  );
查看更多
后来的你喜欢了谁
6楼-- · 2018-12-30 23:54

We just had to work around this problem and tested three different approaches.

  1. does cancel the request as suggested by @meouw
  2. execute all request but only processes the result of the last submit
  3. prevents new requests as long as another one is still pending

var Ajax1 = {
  call: function() {
    if (typeof this.xhr !== 'undefined')
      this.xhr.abort();
    this.xhr = $.ajax({
      url: 'your/long/running/request/path',
      type: 'GET',
      success: function(data) {
        //process response
      }
    });
  }
};
var Ajax2 = {
  counter: 0,
  call: function() {
    var self = this,
      seq = ++this.counter;
    $.ajax({
      url: 'your/long/running/request/path',
      type: 'GET',
      success: function(data) {
        if (seq === self.counter) {
          //process response
        }
      }
    });
  }
};
var Ajax3 = {
  active: false,
  call: function() {
    if (this.active === false) {
      this.active = true;
      var self = this;
      $.ajax({
        url: 'your/long/running/request/path',
        type: 'GET',
        success: function(data) {
          //process response
        },
        complete: function() {
          self.active = false;
        }
      });
    }
  }
};
$(function() {
  $('#button').click(function(e) {
    Ajax3.call();
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="button" type="button" value="click" />

In our case we decided to use approach #3 as it produces less load for the server. But I am not 100% sure if jQuery guarantees the call of the .complete()-method, this could produce a deadlock situation. In our tests we could not reproduce such a situation.

查看更多
荒废的爱情
7楼-- · 2018-12-30 23:55

I was doing a live search solution and needed to cancel pending requests that may have taken longer than the latest/most current request.

In my case I used something like this:

//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 
查看更多
登录 后发表回答