这是滚动时调用请求的javascript
$(document).ready(function(){
var tempScrollTop, currentScrollTop = 0;
$(document).scroll(function(){
currentScrollTop = $(document).scrollTop();
var ids = new Array();
if (tempScrollTop < currentScrollTop )
{
var result = currentScrollTop % 100;
if(result == 0)
{
//console.log('scroll happened');
var items = $(".item");
var items_l = items.length;
for(var i = 0; i < items_l; i++)
{
ids[i] = parseInt(items[i].id.replace(/\D+/g,""));
}
ids = ids.sort();
var last_id = ids[0];
$.ajax({
url: "ajax/load",
type: "POST",
data: {last_id : last_id},
success: function(res){
$("#content").append(res);
}
});
}
}
/*else if (tempScrollTop > currentScrollTop )
{
var result = currentScrollTop % 100;
if(result == 0)
{
$("#content").text("Вверх запрос " + result);
}
}*/
tempScrollTop = currentScrollTop;
})
});
这是控制器方法:
public function ajaxLoad()
{
$last_id = intval($this->input->post("last_id"));
//$last_id++;
$db_data['query'] = $this->db->query("SELECT * FROM items WHERE id < ".$last_id." ORDER BY id DESC LIMIT 1");
$data['content'] = $this->load->view('item', $db_data, true);
echo $data['content'];
}
我有两个问题:
1)我如何防止双重请求有时会使2个相同的记录被输出?当我向下滚动
2)我怎么能让每100个像素的滚动记录都附加,但问题是很难使currentScrollTol%100 == 0,我怎么能把它改成正常?
答案 0 :(得分:0)
这个怎么样?
var tempScrollTop, currentScrollTop = 0, isLoading = false;
$(document).scroll(function(){
[...剪辑...]
var last_id = ids[0];
if ( !isLoading ) {
isLoading = true;
$.ajax({
url: "ajax/load",
type: "POST",
data: {last_id : last_id},
success: function(res){
$("#content").append(res);
isLoading = false;
},
error: function() { isLoading = false; } // just in case
});
[...等......]
当然这只会让你一次加载一件东西,但至少它不会锁定你的UI。
您还可以将last_id值存储在更高的范围内(有点像布尔值)并使用它来确保您不再加载相同的东西......这两种方法都有它们的缺陷,但它可能适合你的需求。
-m1
答案 1 :(得分:0)
所以你有两个问题:
1)你并不总是达到%100条件
2)你有时会不止一次地达到%100的状态
我会建议像:
$(document).ready(function(){
var tempScrollTop, currentScrollTop = 0;
var loaded = {};
loaded[0] = true; //assuming the first piece comes loaded
$(document).scroll(function(){
currentScrollTop = $(document).scrollTop();
var ids = new Array();
//this gives you a different int value for each 100 px section
//at 67px, you get 0, at 345px you get 3, etc
int section = Math.floor(currentScrollTop/100)
if(!loaded[section]) {
//prevents double request
loaded[section] = true;
var items = $(".item");
var items_l = items.length;
for(var i = 0; i < items_l; i++)
{
ids[i] = parseInt(items[i].id.replace(/\D+/g,""));
}
ids = ids.sort();
var last_id = ids[0];
$.ajax({
url: "ajax/load",
type: "POST",
data: {last_id : last_id},
success: function(res){
$("#content").append(res);
}
});
}
});
});
我还要注意,如果你在向下滚动一下后重新加载这些解决方案,包括原始解决方案,将会出现一些问题,因为浏览器将跳转到您滚动到的点而不调用滚动事件来生成高于该点的页面。但这超出了问题的范围。