我在我的项目中使用无限滚动。首先它会从 MySQL 数据库中获取一些记录并显示在页面上。一旦页面向下滚动,它就会向服务器进行 ajax 查询并加载更多数据。
是否可以一次性从mysql数据库中以json格式获取所有数据,然后在客户端执行load more。所以,基本上我不想向数据库发出 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 查询所需的时间。
关于javascript - 无限滚动: Load all data from database and scroll to show more,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806449/