Ajax GET被调用两次(在Endless Scroll中)

时间:2015-10-24 21:11:13

标签: javascript jquery html ajax pagination

我有一个由ajax和jQuery制作的无休止的滚动。它使用在Controller(Laravel5)中分页的项目,使用ajax获取它。

一切正常,但我有问题。当我点击页面底部时,它会进行两次ajax调用。我怀疑它是因为setInterval,因为当我改变时间时,它会影响到那个部分。

// Creates the pagination pages [<[1]2]3]>]
{!! $boxes->render() !!}

// Html
        <input type="hidden" id="page" value="1" />
        <input type="hidden" id="max_page" value="{{{ $boxes-id }}}" />
        <div id="end_of_page" class="center">
            <hr/>
            <span>End of the feed.</span>

<script>
  $(document).ready(function() {

    var didScroll = false;

       $(window).scroll(function() { //watches scroll of the window
             didScroll = true;
       });


       //Sets an interval so your window.scroll event doesn't fire constantly. This waits for the user to stop scrolling for not even a second and then fires the pageCountUpdate function (and then the getPost function)
    setInterval(function() {
        if (didScroll){
           didScroll = false;
           if(($(document).height()-$(window).height())-$(window).scrollTop() < 10){
                  pageCountUpdate();
            }
        }
    }, 250);  

例如,当我将250更改为5000时,它会给出介于两者之间的时间,但这不是我想要的。一旦我触及底部,我想只调用一次,可能用布尔变量禁用它,然后在新元素加载后重新激活它(在ajax成功状态下),但我无法弄清楚它在哪里把阻塞变量。

//Continuing

    function pageCountUpdate(){
          var page = parseInt($('#page').val());
          var max_page = parseInt($('#max_page').val());

          if(page < max_page){
              $('#page').val(page+1);
              getPosts();
              $('#end_of_page').hide();
          } else {
              $('#end_of_page').fadeIn();
          }
      }

    function getPosts(){
        var data = { "page": $('#page').val() }
        $.ajax({
                type: "POST",

                //Classic ajax call

                beforeSend: function(){
                ..}
                complete: function(){
                ..}
                success: function(){
                ..}    
        });
    }

 } 
});

更新:关于John Resig在评论中提到的示例,我需要使用var outerPane = $details.find(".details-pane-outer"), didScroll = false;。我认为没有这个部分会产生我的问题,但我无法通过find()方法找出选择的位置。

1 个答案:

答案 0 :(得分:1)

除了你奇怪的setinterval结构(只是将代码移动到滚动事件,没有间隔)。

似乎在页面底部的最后10个像素内多次调用scroll事件。因此,当滚动到底部时,距离底部9 px处,事件被触发,从而加载更多帖子。但即使在加载新帖子之前,同时你再滚动一点再次触发滚动事件。这会使您的帖子加载两次甚至两次以上。

要解决这个问题,您可以添加一个简单的布尔开关,确保帖子在已经加载时不会再次加载。类似的东西:

var loading=false;
function onReachScrollLimit(){
    if(loading){return;}
    loading=true;
    load_new_posts();
}
function load_new_posts(){
    //insert the posts
    loading=false;
}
相关问题