【发布时间】:2015-11-17 06:33:47
【问题描述】:
这里我有一个数据库请求:
$query = mysqli_query($db, "
SELECT * FROM posts p INNER JOIN friends f ON
((p.from_user=f.user1 OR p.from_user=f.user2) AND (f.user1='$ownid' OR f.user2='$ownid') AND f.accepted='1')
GROUP BY p.id ORDER BY p.uhrzeit DESC ;
");
还有一个用于检查滚动位置的简单 Javascript。
$(window).scroll(function () {
if ($(this).scrollTop() > 1500) {
}
});
当然,这些只是没有文档就绪功能等的代码片段。
我现在的问题是:每次触发滚动功能时,如何通过 Ajax 请求获取页面加载时的前 15 个结果?
我怎样才能在我的实际查询中实现这一点?
感谢您的每一个回答。 如果有遗漏的信息请索取,我会更新。
编辑 我现在做了什么
JS
var offset = 15,
scrollEnd = false;
$(window).scroll(function(){
if($(window).scrollTop() >= $('.footer').offset().top && typeof scrollEnd !== 'undefined' && !scrollEnd){
alert();
$.ajax({
url: "./ajax/loadmore_homeposts.php",
data : {offset: offset},
beforeSend: function(){
scrollEnd = true;
}
success:function(r){
if(r.data.length){
// + you have result
offset *=2;
// prepare the html and append into the respective container
alert(r);
scrollEnd = false;
}else{
alert("<p>No more result</p>");
$('.result_container').append('<p>No more result</p>');
}
}
})
}
});
PHP
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$ownid= $_SESSION['SESSION'];
$offset = isset($_GET['offset']) ? $_GET['offset'] : 0;
$limit = 15;
$query=mysqli_query($db,
"
SELECT * FROM posts p INNER JOIN friends f ON
((p.from_user=f.user1 OR p.from_user=f.user2) AND (f.user1='$ownid' OR f.user2='$ownid') AND f.accepted='1')
GROUP BY p.id ORDER BY p.uhrzeit DESC limit $offset,$limit;
");
$data = [];
while(($row = mysqli_fetch_array($result))){
$data[] = $row;
}
echo json_encode( ['data'=>$data]);
?>
【问题讨论】:
-
起初您的滚动检查不正确。您不应该使用常量检查 scrollTop ,您应该检测页脚的偏移量顶部,然后确定您的滚动偏移量更大或接近页脚偏移量,所以这意味着用户已经向下滚动到页脚,所以你有加载新内容
-
你能给我一个例子吗?会很棒:)
标签: javascript php jquery ajax mysqli