我的网站有一部分需要在用户到达底部时动态加载内容。我正在使用jQuery,这是检测滚动的代码:
$(document).ready(function() {
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("Bottom reached");
$('div#loadMoreComments').show();
dataStr = "from=" + $(".n:last").attr('id')
$.ajax({
type: "POST",
url: "ajax/query.php",
data: dataStr,
success: function(html) {
if(html){
$("#hold").append(html);
alert("Data was added");
}
else{
$('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>End of countries !!!!!!!</h1></center>");
alert("Data was not added");
}
}
});
}
});
});
我遇到的第一个问题是只有当用户到达页面顶部时才会检测到向下滚动。第二个问题是它根本没有加载任何内容,因为似乎没有发布变量,这是我在query.php中的代码:
if(array_key_exists('from', $_POST)) {
$from = htmlspecialchars(stripslashes(mysql_real_escape_string($_POST['from'])));
$to = 15;
$re = ("SELECT status as status, sid as sid, UNIX_TIMESTAMP(timestamp) as timestamp FROM mingle_status WHERE uid = '$uid' ORDER BY timestamp DESC LIMIT $from,$to"); //query
}
else {
$re = ("SELECT id as id, status as status, sid as sid, UNIX_TIMESTAMP(timestamp) as timestamp FROM mingle_status WHERE uid = '$uid' ORDER BY timestamp DESC LIMIT 1"); //query
}
$result = mysql_query($re) or die (mysql_error());
while($st = mysql_fetch_assoc($result)) {
$status = nl2br($st['status']);
$sid = $st['sid'];
$td = $st['timestamp'];
$id = $st['id'];
?>
<div id="<?php echo $id; ?>" class="id">
<!-- stuff -->
</div>
<?php
}
?>
错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '",15' at line 1
如果有人能帮助我,那就太好了,我真的很感激。
编辑:好的,我现在可以生成div了,但只有当我滚动到页面顶部时,它才会附加一个div,如果我再次滚动到顶部,它附加完全相同的div。
答案 0 :(得分:3)
这是错的:
$from = htmlspecialchars(stripslashes(mysql_real_escape_string($_POST['from'])));
如果from
应该是一个整数,只需使用:
$from = (int) $_POST['from'];
我也看到该号码来自html中的id,而ids不能以数字开头。
编辑:另一个问题是,如果存在from
,您不会在SQL查询中选择ID,即使您这样做,这种方法也会导致问题将来删除记录时,您的ID不再是连续的。
关于第一个问题,我可以在萤火虫改变中解决这个问题:
if($(window).scrollTop() + $(window).height() == $(document).height()) {
为:
if( ($(window).scrollTop() + $(window).height()) > ($(document).height() - 10) ) {
编辑2 要解决非顺序ID问题,最简单的方法是使用以下内容在javascript中计算from
:
dataStr = "from=" + $(".n").length; // just count the number of elements you are showing already