代码如下:
$(window).scroll(function(){ var scrolltop=$(window).scrollTop(); var wheight=$(window).height(); var dheight=$(document).height(); if(scrolltop>dheight-wheight-20){ page++; $.ajax({ type: "GET", url: url+"page/"+page, dataType: "json", success: function(data){ $("#list").append(html字符串); } } })
发现chrome开发者工具里显示发送多次请求,
求解决方案!
function performScroll(){ var scrolltop=$(window).scrollTop(); var wheight=$(window).height(); var dheight=$(document).height(); if(scrolltop>dheight-wheight-20){ page++; $(window).unbind('scroll'); $.ajax({ type: "GET", url: url+"page/"+page, dataType: "json", success: function(data){ $("#list").append(html字符串); $(window).bind('scroll',performScroll); } } } $(window).bind('scroll',performScroll);
// 增加一个变量记录是否处于请求中 var flag = true; $(window).scroll(function(){ var scrolltop=$(window).scrollTop(); var wheight=$(window).height(); var dheight=$(document).height(); if(scrolltop>dheight-wheight-20 && flag){ // 开始请求的时候,将状态置false; // 这样就算高度达到请求标准也无法进入请求状态 flag = false; page++; $.ajax({ type: "GET", url: url+"page/"+page, dataType: "json", success: function(data){ $("#list").append(html字符串); // 将标志置为true,这样当高度再次达到标准时,可以执行请求 flag = true; } } })