当用户成功到达页面底部时,我的代码会加载新数据,但是当加载来自数据库的所有帖子时,代码会尝试获取更多帖子,导致页面卡住几秒钟。我需要的是检测何时从DB加载最后一篇文章并阻止代码执行的机制。
function yHandler(){
var id=$(".output:last").attr("id");
var split = id.split("output");
var newid=split[1];
var awrap = document.getElementById('awrap');
var contentHeight = awrap.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
var sesid=$("#sesid").val();
if(y >= contentHeight){
// Ajax call to get more dynamic data goes here
$.ajax({
url:"load.php",
type:"POST",
data:'did=' + did + '&newid=' + newid + '&id=' + id + "&sesid=" + sesid,
success:function(data){
$("#newdata").append(data);
});
} ///if end
} /// FUNC END
window.onscroll = yHandler;
load.php //
$osql=mysql_query("SELECT * FROM answer WHERE respond IS NOT NULL AND question_id='$did' AND id < '$newid' and pinned = '0' ORDER BY resp_time DESC LIMIT 5");
/// while loop which fetches data is below
答案 0 :(得分:0)
如果您不想或不需要处理当用户在此网页上时其他帖子可以通过其他方式显示的情况,那么您可以在没有更多帖子时设置标记并检查如果设置了该标志,则标记并避免调用load.php
。
// flag so we know when there are no more posts
var noMorePosts = false;
function yHandler(){
var id=$(".output:last").attr("id");
var split = id.split("output");
var newid=split[1];
var awrap = document.getElementById('awrap');
var contentHeight = awrap.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
var sesid=$("#sesid").val();
if(!noMorePosts && y >= contentHeight){
// Ajax call to get more dynamic data goes here
$.ajax({
url:"load.php",
type:"POST",
data:'did=' + did + '&newid=' + newid + '&id=' + id + "&sesid=" + sesid,
success:function(data){
// pseudo code check to see if data was empty
// you fill in the actual test here
if (nothing in data) {
noMorePosts = true;
} else {
$("#newdata").append(data);
}
});
}
}
答案 1 :(得分:0)
您可以从后端返回执行的时间戳,然后在客户端请求此时间戳再次检索数据。就像缓存一样。
(我会在一分钟内给你其他选择)
这可能是另一种方式(按请求数据缓存):
function yHandler(){
yHandler.lastRequest = yHandler.lastRequest || null;
var id=$(".output:last").attr("id");
var split = id.split("output");
var newid=split[1];
var awrap = document.getElementById('awrap');
var contentHeight = awrap.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
var sesid=$("#sesid").val();
if(y >= contentHeight){
// Ajax call to get more dynamic data goes here
var newRequest = 'did=' + did + '&newid=' + newid + '&id=' + id + "&sesid=" + sesid;
if(newRequest != yHandler.lastRequest){
$.ajax({
url:"load.php",
type:"POST",
data: yHandler.lastData,
success:function(data){
$("#newdata").append(data);
yHandler.lastData = newRequest; //Save the last request data
}
});
}
}
});
基本上,上面的代码保存了最后一个请求data
。如果在下一个滚动中没有更改,则不要执行ajax调用。
希望这会有所帮助。干杯