在新请求中中止先前的ajax请求

时间:2013-10-08 09:46:34

标签: javascript ajax jquery

我有一个函数在更改输入时运行ajax调用。

但是,在前一个ajax调用完成之前,有可能再次触发该函数。

我的问题是,如何在开始新的ajax之前中止之前的ajax调用? 不使用全局变量。 (参见类似问题的回答here

jsfiddle我当前的代码:

使用Javascript:

var filterCandidates = function(form){
    //Previous request needs to be aborted.
    var request = $.ajax({
        type: 'POST',
        url: '/echo/json/',
        data: {
            json: JSON.stringify({
                count: 1
            })
        },
        success: function(data){
            if(typeof data !== 'undefined'){
                jQuery('.count').text(data.count)
                console.log(data.count);
            }
        }
    });
};

if(jQuery('#search').length > 0){
    var form = jQuery('#search');
    jQuery(form).find(':input').change(function() {
        filterCandidates(form);
    });
    filterCandidates(form);
}

HTML:

<form id="search" name="search">
    <input name="test" type="text" />
    <input name="testtwo" type="text" />
</form>
<span class="count"></span>

5 个答案:

答案 0 :(得分:91)

 var currentRequest = null;    

currentRequest = jQuery.ajax({
    type: 'POST',
    data: 'value=' + text,
    url: 'AJAX_URL',
    beforeSend : function()    {           
        if(currentRequest != null) {
            currentRequest.abort();
        }
    },
    success: function(data) {
        // Success
    },
    error:function(e){
      // Error
    }
});

答案 1 :(得分:9)

var filterCandidates = function(form){
    //Previous request needs to be aborted.
    var request = $.ajax({
        type: 'POST',
        url: '/echo/json/',
        data: {
            json: JSON.stringify({
                count: 1
            })
        },
        success: function(data){
            if(typeof data !== 'undefined'){
                jQuery('.count').text(data.count)
                console.log(data.count);
            }
        }
    });
    return request;
};

var ajax = filterCandidates(form);

保存在变量中,然后在发送第二次之前,检查其readyState并在需要时调用abort()

答案 2 :(得分:2)

已接受答案的变体,并从对问题的评论中采纳-这对我的应用非常有用。...

使用jQuery的$ .post()....

var request = null;

function myAjaxFunction(){
     $.ajaxSetup({cache: false}); // assures the cache is empty
     if (request != null) {
        request.abort();
        request = null;
     }
     request = $.post('myAjaxURL', myForm.serialize(), function (data) {
         // do stuff here with the returned data....
         console.log("returned data is ", data);
     });
}

根据需要多次调用myAjaxFunction(),它将杀死除最后一个以外的所有内容(我的应用程序具有“日期选择器”,并根据选择的日期更改价格-当有人快速单击它们而没有上面的代码时,就可以判断出他们是否会获得正确的价格。使用它,可以100%正确!)

答案 3 :(得分:0)

试试此代码

var lastCallFired=false;

var filterCandidates = function(form){

    if(!lastCallFired){
    var request = $.ajax({
        type: 'POST',
        url: '/echo/json/',
        data: {
            json: JSON.stringify({
                count: 1
            })
        },
        success: function(data){
            if(typeof data !== 'undefined'){
                jQuery('.count').text(data.count)
                console.log(data.count);
            }
        }
    });
        setInterval(checkStatus, 20);

    }

};

if(jQuery('#search').length > 0){
    var form = jQuery('#search');
    jQuery(form).find(':input').change(function() {
        filterCandidates(form);
    });
    filterCandidates(form);
}

var checkStatus = function(){
        if(request && request.readyState != 4){
            request.abort();
        }
    else{
        lastCallFired=true;
    }
};

答案 4 :(得分:0)

if(typeof window.ajaxRequestSingle !== 'undefined'){
  window.ajaxRequestSingle.abort();
}

window.ajaxRequestSingle = $.ajax({
  url: url,
  method: 'get',
  dataType: 'json',
  data: { json: 1 },
  success: function (data) {
    //...
  },
  complete: function () {
    delete window.ajaxRequestSingle;
  }
});