[英]Infinite scroll causing random number 1 to print before actual data
我能够使滚动条正常工作,可以让它加载滚动条上的下5个项目,但是在下一个5个项目出现之前,在结果上方插入数字1,并且一直重复到最后。 一旦到达末尾,滚动将继续打印数字1,就好像卡在滚动循环中一样。
另一个需要注意的奇怪之处是,如果滚动速度太快,记录将重复,就像查询运行两次一样。
下面的scroll.php代码:
<div class="col-md-12" id="post-data">
<?php
require('config.php');
$sql = "SELECT postID, postTitle, postDesc FROM blog_posts ORDER BY postID DESC LIMIT 5";
$result = $conn->query($sql);
?>
<?php include('data.php'); ?>
</div>
<div class="ajax-load text-center" style="display:none">
<p><img src="loader.gif"> Loading More post</p>
</div>
<script type="text/javascript">
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
var last_id = $(".post-id:last").attr("id");
loadMoreData(last_id);
}
});
function loadMoreData(last_id){
$.ajax(
{
url: '/loadMoreData.php?last_id=' + last_id,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
$('.ajax-load').hide();
$("#post-data").append(data);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
data.php代码如下:
<?php
while($post = $result->fetch_assoc()){
?>
<div class="post-id" id="<?php echo $post['postID']; ?>">
<h3><a href=""><?php echo $post['postTitle']; ?></a></h3>
<p><?php echo $post['postDesc']; ?></p>
<div class="text-right">
<button class="btn btn-success">Read More</button>
</div>
<hr style="margin-top:5px;">
</div>
<?php
}
?>
下面的loadMoreData.php代码:
<?php
require('config.php');
$sql = "SELECT postID, postTitle, postDesc FROM blog_posts
WHERE postID < '".$_GET['last_id']."' ORDER BY postID DESC LIMIT 5";
$result = $conn->query($sql);
$json = include('data.php');
echo json_encode($json);
?>
将loadMoreData.php更改为bwlow。 删除echo json_encode($json);
从最后开始
<?php
require('config.php');
$sql = "SELECT postID, postTitle, postDesc FROM blog_posts
WHERE postID < '".$_GET['last_id']."' ORDER BY postID DESC LIMIT 5";
$result = $conn->query($sql);
include('data.php');
?>
更新
停止滚动直到上一个ajax调用完成。 您可以使用标志变量
<script type="text/javascript">
loaded = true; //<-----Initialize
$(window).scroll(function() {
if(($(window).scrollTop() == $(document).height() - $(window).height()) && loaded) { //<-----Add in condition
var last_id = $(".post-id:last").attr("id");
loadMoreData(last_id);
}
});
function loadMoreData(last_id){
loaded = false; //<----- change it to false as soon as start ajax call
$.ajax(
{
url: '/loadMoreData.php?last_id=' + last_id,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
$('.ajax-load').hide();
$("#post-data").append(data);
loaded = true; //<--- again change it to true
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
loaded = true;
});
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.