在新请求中中止先前的ajax请求 [英] Abort previous ajax request on new request

查看:141
本文介绍了在新请求中中止先前的ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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之前中止之前的ajax调用?
不使用全局变量。 (请参阅此处的类似问题的答案)

My question is, how would I abort the previous ajax call before starting a new one? Without using a global variable. (See answer to a similar question 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>


推荐答案

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

这篇关于在新请求中中止先前的ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆