我正在尝试创建一个包含帖子的无限滚动页面。我有这个HTML代码:
<div class="content">
<div class="c" id="adata">
<!-- the posts goes here -->
</div>
<div class="card" id="scroll-to">
<div class="ajax-load text-center" style="display:none">
<p><img src="/img/loader.gif">Loading More post</p>
</div></div>
</div>
当用户使用id="scroll-to"
滚动到div时。我已经创建了一个代码的ajax调用,该代码自动将数据附加到具有id="adata"
的div。
要创建ajax调用,我使用了jquery代码,如下所示:
$(window).scroll(function() {
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
var last_id = $(".box:last").attr("id");
$('.ajax-load').show();
loadMoreData(last_id);
}
});
function loadMoreData(last_id){
$.ajax(
{
url: '/loadMoreData.php?last_id=' + last_id,
type: "get",
})
.done(function(data)
{
if(data.html == " "){
$('.ajax-load').html("No more records found");
return;
}
$('.ajax-load').hide();
$('#adata').append(data);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
但是,每当用户使用id="scroll-to"
滚动到div时,上面的jquery代码会在相同/单个实例上创建多个ajax调用到/loadMoreData.php?last_id=' + last_id
,并将last_id
替换为最后一个帖子的id。
假设最后一篇文章的id是2177,jquery代码创建了多个ajax请求到URL /loadMoreData.php?last_id=2177
,这真的不应该超过一次,似乎无法理解为什么?
由于多次请求使用相同的last_id
,帖子会重复出现。这个问题的理想解决方案是什么?
要更好地了解问题,您可以访问http://funpd.com/index1。
你需要为你的请求实现一种'看门狗' - 创建布尔变量并在你要执行请求时检查它,简单的例子:
var isDownloading = false;
function loadMoreData(last_id) {
if (isDownloading) return;
isDownloading = true;
$.ajax({
url: '/loadMoreData.php?last_id=' + last_id,
type: "get",
}).done(function(data) {
isDownloading = false;
if (data.html == " ") {
$('.ajax-load').html("No more records found");
return;
}
$('.ajax-load').hide();
$('#adata').append(data);
}).fail(function(jqXHR, ajaxOptions, thrownError) {
isDownloading = false;
alert('server not responding...');
});
}
这似乎是预期的行为,因为页面仍然会滚动到您到达的div之下。 AJAX将无法完成,因此会立即附加html。
在loadMoreData之前放置一个if语句,检查ajax是否正在加载,例如,重置check done on done。