防止堆叠AJAX请求

Mar*_*son 4 javascript php jquery

我遇到了一个我似乎无法解决的问题.

我目前正在实现一个类似于Twitter使用的AJAX功能 - 在滚动时获取新帖子.

jQuery看起来像这样:

        $(window).scroll(function(){
            if($(window).scrollTop() == $(document).height() - $(window).height()){
                $('div#ajaxloader').show();
                $.ajax({
                    url: "loader.php?lastid=" + $(".container:last").attr("id"),
                    success: function(html){
                        if(html){
                            $("#main").append(html);
                            $('div#ajaxloader').hide();
                        }else{
                            $('div#ajaxloader').html('No more posts to show.');
                        }
                    }                   
                });
            }
        });
Run Code Online (Sandbox Code Playgroud)

现在问题; 如果用户滚动得非常快并且数据库正在快速完成工作 - jQuery似乎无法足够快地发送正确的id作为查询 - 这导致双帖.

任何人都知道如何防止这种情况?

ITr*_*ubs 5

试试这个:

  var runningRequest = 0;
  $(window).scroll(function(){
        if(runningRequest <1){
        if($(window).scrollTop() == $(document).height() - $(window).height()){
            runningRequest++;
            $('div#ajaxloader').show();
            $.ajax({
                url: "loader.php?lastid=" + $(".container:last").attr("id"),
                success: function(html){
                    runningRequest--;
                    if(html){
                        $("#main").append(html);
                        $('div#ajaxloader').hide();
                    }else{
                        $('div#ajaxloader').html('No more posts to show.');
                    }
                }
                error: function(){runningRequest--;}                   
            });
        }
        }
    });
Run Code Online (Sandbox Code Playgroud)