简体   繁体   English

在完成上一个请求之前中止新的 AJAX 请求

[英]Abort new AJAX request before completing the previous one

I have a function that runs an AJAX call on the change of an input.我有一个函数可以在输入更改时运行 AJAX 调用。

But, there is a chance that the function will be fired again before the previous ajax call has completed.但是,有可能在前一个 ajax 调用完成之前再次触发该函数。

My question is, how would I abort the previous AJAX call before starting a new one?我的问题是,在开始新的 AJAX 调用之前,我将如何中止之前的 AJAX 调用? Without using a global variable.不使用全局变量。 (See answer to a similar question here ) (请参阅此处对类似问题的回答)

JSFiddle of my current code:我当前代码的JSFiddle

Javascript: 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: HTML:

<form id="search" name="search">
    <input name="test" type="text" />
    <input name="testtwo" type="text" />
</form>
<span class="count"></span>
 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
    }
});
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);

save in a variable, and then, before sending second time, check its readyState and call abort() if needed保存在一个变量中,然后在第二次发送之前检查它的readyState并在需要时调用abort()

a variation on the accepted answer and adopted from a comment on the question - this worked great for my application....已接受答案的变体并从对问题的评论中采用 - 这对我的应用程序很有用....

using jQuery's $.post()....使用 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);
     });
}

Call myAjaxFunction() as many times as you like and it kills all except the last one (my application has a 'date selector' on it and changes price depending on the days selected - when someone clicks them fast without the above code, it is a coin toss as to if they will get the right price or not. With it, 100% correct!)根据需要多次调用 myAjaxFunction(),它会杀死除最后一个之外的所有内容(我的应用程序上有一个“日期选择器”,并根据所选日期更改价格 - 当有人在没有上述代码的情况下快速点击它们时,它是抛硬币看他们是否会得到正确的价格。有了它,100% 正确!)

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;
  }
});

Try this code试试这个代码

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;
    }
};

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

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