我有一个从表中返回16条记录的页面。
当用户滚动到底部时,我从表中提取另外12条记录,并将它们附加到以前的结果中,我的问题是我的结果被重复,而且顺序不正确。
JS
// Ajax Getentries.php
var url = location.pathname;
if(url.indexOf('missing-people.php') > -1) {
didScroll = false;
$(window).scroll(function () {
didScroll = true;
});
setInterval(function () {
if(didScroll) {
didScroll = false;
if(($(document).height() - $(window).height()) - $(window).scrollTop() < 100) {
var number = $(".directory").children().length;
$.ajax({
type: "POST",
url: "getentries.php",
data: "count=" + number,
success: function (results) {
$('.directory').append(results).fadein();
}
});
}
}
}, 250);
}
PHP
$result = mysql_query("SELECT * FROM directory LIMIT {$_POST['count']},12");
$c = 1;
while($row = mysql_fetch_array($result))
{
echo '<div class="entry';
if (($c % 4) == 1) echo ' alpha ';
echo ' span3"><span class="name">' . $row['First_Name'] . ' ' . $row['Surname'] . "</span>";
echo '<a href="/missing-people/' . strtolower($row["Location_County_Last_Seen"]) . '/' . strtolower($row["First_Name"]) . '-' . strtolower($row["Surname"]) . '/' . $row["ID"] . '"><img src="/access/upload/' . $row["picture_1"] . '" alt="' . $row['First_Name'] . ' ' . $row['Surname'] . ', missing since ' . $row['Date_Last_Seen'] . ' " /></a>';
echo '<span class="missing-from">Last seen in ' . ucwords($row["Location_County_Last_Seen"]) . '</span><a href="/missing-people/' . strtolower($row["Location_County_Last_Seen"]) . '/' . strtolower($row["First_Name"]) . '-' . strtolower($row["Surname"]) . '/' . $row["ID"] . '">View Profile</a></div>';
$c++;
}
mysql_close($con);
这似乎是一个竞赛条件。事实上,如果你快速滚动页面,就会发生这种情况:
- setInterval被触发
- dom中已经有12个图像,因此
var number = $(".directory").children().length
是12 - 现在,使用ajax从服务器获取新数据
现在,如果我仍然在页面的底部,ajax调用还没有完成,那么setInterval将再次被触发,number
仍然解析为12,我将执行相同的ajax请求。因此重复。
解决这个问题很简单,只需在脚本开始时设置number
,并在每次进行ajax调用时将其递增即可。
// Ajax Getentries.php
var url = location.pathname;
var number = $(".directory").children().length;
if(url.indexOf('missing-people.php') > -1) {
didScroll = false;
$(window).scroll(function () {
didScroll = true;
});
setInterval(function () {
if(didScroll) {
didScroll = false;
if(($(document).height() - $(window).height()) - $(window).scrollTop() < 100) {
number += 12;
$.ajax({
type: "POST",
url: "getentries.php",
data: "count=" + number,
success: function (results) {
$('.directory').append(results).fadein();
}
});
}
}
}, 250);
}