我很难计算如何避免重复ajax调用我的无限滚动JavaScript代码。 它主要工作,但有时我有2或3次相同的Ajax页面调用导致一种循环。 如何避免这种情况? 感谢无限滚动重复ajax调用
//infiniteScroll
var currentPage = 1;
var intervalID = -1000;
var scroll = false;
$('document').ready(function(){
if (scroll == true) {
if (window.location.pathname == "/" && window.location.search == "" && $('#items_container').length > 0) {
$('.pagination').hide();
intervalID = setInterval(checkScroll, 300);
}
};
})
function checkScroll() {
if (nearBottomOfPage()) {
currentPage++;
jQuery.ajax('?page=' + currentPage, {asynchronous:true, evalScripts:true, method:'get',
beforeSend: function(){
var scroll = false;
$('.spinner').show();
},
success: function(data, textStatus, jqXHR) {
$('.spinner').hide();
$('#items_container').append(jQuery(data).find('#items_container').html());
var scroll = true;
if(typeof jQuery(data).find('.item').html() == 'undefined' || jQuery(data).find('.item').html().trim().length == 0 || currentPage == 10){
clearInterval(intervalID);
}
},});
}
}
}
function nearBottomOfPage() {
return scrollDistanceFromBottom() < 450;
}
function scrollDistanceFromBottom(argument) {
return pageHeight() - (window.pageYOffset + self.innerHeight);
}
function pageHeight() {
return Math.max(document.body.scrollHeight, document.body.offsetHeight);
}
增加新的数据每一次,你有充分的时间AJAX调用 –
你*会*得到多个触发事件与您的代码,所以你需要标志负载进行中状态,例如通过属性。使用该属性决定调用您的Ajax代码,因此您不会重复请求相同的页面。完成后(成功或失败),清除该属性。你也可以尝试一下那里的许多免费无限滚动条。有些是符合Google的(通过使用页面上现有的分页链接)。 –