页面滚到底部自动加载加载出现请求多次bug

代码如下:

$(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开发者工具里显示发送多次请求,图片描述

求解决方案!

阅读 2.8k
2 个回答
//    增加一个变量记录是否处于请求中
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;
            }
    }
})
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);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题