无限滚动:从数据库加载所有数据并滚动以显示更多


infinity scroll: Load all data from database and scroll to show more

>我在我的项目中使用了无限滚动。首先,它将从MySQL数据库中获取一些记录并显示在页面上。页面向下滚动后,它会对服务器进行 ajax 查询并加载更多数据。

是否可以一次从mysql数据库中以json格式获取所有数据,然后在客户端执行更多加载。所以,基本上我不想对数据库发出ajax请求。

如果我在页面滚动时发出 ajax 请求,这是工作正常的代码。

flag = true;
$(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() == $(document).height()){
        first = $('#first').val();
        limit = $('#limit').val();
        no_data = true;
        if(flag && no_data){
            flag = false;
            $('#loader').show();
            $.ajax({
                url : 'ajax_html.php',
                method: 'post',
                data: {
                   start : first,
                   limit : limit
                },
                success: function( data ) {
                    flag = true;
                    $('#loader').hide();
                    if(data !=''){
                        first = parseInt($('#first').val());
                        limit = parseInt($('#limit').val());
                        $('#first').val( first+limit );
                        $('#timeline-conatiner').append( '<li class="year">'+year+'</li>');
                        $('#timeline-conatiner').append( data );
                        year--;
                    }else{
                        alert('No more data to show');
                        no_data = false;
                    }
                },
                error: function( data ){
                    flag = true;
                    $('#loader').hide();
                    no_data = false;
                    alert('Something went wrong, Please contact admin');
                }
            });
        }

    }
}); 

这是未经测试的,只是该方法的一个例子,对不起,我没有时间做一个完整的例子,但这应该给你一个想法。

 //data cache
 var cache = ['one','two', 'three' .....];
 //current location in cache
 var current = 0; 
 //ajax request object
 var request;
 if($(window).scrollTop() + $(window).height() == $(document).height()){
      var cache_total = cache.length;
      //add next item to page & increase the current pointer
      $('#timeline-conatiner').append( cache[current] );
      ++current;
      if( current - cache.length < 50 ){
           //if we only have 50 items not shown in cache pull next results with ajax and add to cache
           if( !request ){
                //also youll want to keep track if you have a pending request that hasn't returned yet, to prevent race conditions.
                request = $.ajax( .... ).success( function( data ){
                     $.extend( cache, data ); //or push each if you like
                }).always( function(){
                     request = false; //should be false on finish but just because.
                });
            } //end if request
       //make sure to properly offset the data using the total in the cache to prevent pulling duplicates. eg SELECT ... LIMIT {cache.length}, 50
      } // end if cached
 } //end scroll

看到上面的问题是用户需要等待ajax调用完成,这本质上将其转换为同步请求(例如重新加载页面)。 您希望像 ajax 一样保持异步。 因此,您不是显示 ajax 的结果,而是缓冲它们并保留一些未显示的数据。 然后在滚动时显示一些缓冲数据,然后填充缓存备份。

显然,这使得编码变得更加复杂,但优点是你不需要一次拉取大量数据,并且用户不会因在 ajax 请求上停止而获得延迟。 您必须平衡请求所需的时间与缓存中的数据量,以便始终有一些数据。 这取决于渲染data需要多少空间以及 ajax 查询需要多长时间。

我会说你根本不需要无限滚动器(或其他任何东西)来做你想做的事......但是由于您已经很好地工作了,我怀疑您可能会决定在某个时候想要"延迟加载"类型的功能,您可以做懒惰的事情......

只需尝试使用示例中的第一个并限制参数值...

说。。。第一个 = 0 和限制=一些非常大的数字...

我认为您可以设置一些值并非常轻松地在页面加载时强制单个 ajax 调用。

如果所有数据都已检索并添加到 DOM,则以下脚本可能会有所帮助。首先hidden类添加到额外的元素中。创建 DOM 后运行此脚本。

$(".elements").each(function(index, el) { // `elements` is the common class for all elements on which this functionality is to be done
    if (index >= maxLimitToShow) { // maxLimitToShow - number of elements to show in the beginning
        $(el).addClass("hidden"); // for extra elements
    }
});

为类hidden添加 css

.hidden {
    display: none;
}

并检查滚动何时到达页面底部以显示更多项目。

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {  // checks if scroll reached at bottom
       var elements = $(".elements.hidden"); // fetch all hidden elements
       elements.each(function (index, el) {
         if (index < singleRowLimit) { // singleRowLimit  - number of elements to show in one scroll
             $(el).removeClass('hidden');
         }
     });
   }
});

编辑 - 不使用CSS - 隐藏/显示

如果所有数据都已检索并添加到 DOM,则以下脚本可能会有所帮助。首先hidden类添加到额外的元素中。创建 DOM 后运行此脚本。

$(".elements").each(function(index, el) { // `elements` is the common class for all elements on which this functionality is to be done
    if (index >= maxLimitToShow) { // maxLimitToShow - number of elements to show in the beginning
        $(el).addClass("hidden").hide(); // for extra elements
    }
});

并检查滚动何时到达页面底部以显示更多项目。

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {  // checks if scroll reached at bottom
       var elements = $(".elements.hidden"); // fetch all hidden elements
       elements.each(function (index, el) {
         if (index < singleRowLimit) { // singleRowLimit  - number of elements to show in one scroll
             $(el).removeClass('hidden').show();
         }
     });
   }
});