另一个ajax请求正在处理时如何防止发送ajax请求?

时间:2013-09-04 19:16:39

标签: javascript ajax jquery

我在一个自动完成搜索框上搜索数据库并返回与搜索相关的用户。我使用jquery ajax来执行此操作。当输入元素发生keyup时,我向`/发送ajax请求ajax / search / url如下:

$("#search").keyup(function(){
    $(".itemSearch").remove();
    $(".notfound").hide();
    $("#searchResultSection").height("70px");
    if(!$("#search").val()){
        $("#searchResultSection").slideUp();
        $(".ajaxLogoSearch").hide();
        $(".notfound").hide();
    }
    else{
        var data = {
            query: $("#search").val()
        };
        $("#searchResultSection").slideDown();
        $(".ajaxLogoSearch").show();
        $.ajax({
            url: '/ajax/search',
            data: data,
            dataType:'json',
            success:function(result){
                if(result.found==0){
                    $(".ajaxLogoSearch").hide();
                    $(".notfound").show();
                }
                else{
                    var searchResult = $("#searchResultSection");
                    $(".ajaxLogoSearch").hide();
                   searchResult.css({"height":20});

                    for(var i=0;i<result.users.length;i++){
                        var content = '<div class="itemSearch">\
                <img src="../../static/social/images/defaultMaleImage.png" height="50px">\
                <p>'+ result.users[i].firstname+ ' '+ result.users[i].lastname +'</p>\
            </div>'
                        if(searchResult.height() < 370){
                            searchResult.height("+=70px");
                        }
                        $("#innerSearch").append(content);
                    }
                    $(".itemSearch").hover(function(){
                        $(this).css({"background":"rgb(55, 108, 221)"});
                    },function(){
                        $(this).css({"background":"#658be6"});
                    });
                }
            }

        });
    }
})

我的问题是当我立即输入2个字母时,发送了2个ajax请求,我在搜索结果框中看到了两次搜索结果。我想要一种方法来防止在第一个未完全完成时发送第二个ajax请求。我该怎么办?这个?

编辑:我终于在codeproject网站上找到了解决方案,感谢您的回答。 this is thte link of the solution

2 个答案:

答案 0 :(得分:2)

更好的方法是在用户停止输入之前不发送请求。使用keydown事件和等待250毫秒不活动的油门很容易完成。按照自己的方式进行操作将导致无法获得用户想要的结果。

$("#search").on("keydown",function(){
    var $this = $(this);
    clearTimeout($this.data("throttle"));
    $this.data("throttle",setTimeout(function(){
        doSearch.call($this.get(0),$this.val()); // perform the ajax search
    },250))
});

此外,在插入新结果时,在单个变量中构建整个结果列表,然后在循环后使用.html(thehtml)一次性插入所有结果。

答案 1 :(得分:0)

您应该创建另一种变量请求。该变量将是当前ajax-request的存储链接。当keyup事件再次触发时,你应该进行检查。

if(request) {
    request.abort();
}
request = $.ajax({/* */});

UPD1:如果第一个ajax-request已完成,则应在成功回调中将请求变量设置为零。

UPD2:订阅更改事件更好

相关问题