javascript - 如何使用 Jquery/Ajax 处理无限滚动的页码?

标签 javascript jquery ajax infinite-scroll

这是我第一次尝试使用 JQuery/Ajax 实现无限滚动。这就是我目前所处的位置:

<script>
$(document).ready(function() {
    // see if we're at the bottom of the page to potentially load more content
    $(window).on('scroll', scrollProducts);

    function scrollProducts() {
        var end = $("#footer").offset().top;
        var viewEnd = $(window).scrollTop() + $(window).height();
        var distance = end - viewEnd;

        // when we're almost at the bottom
        if (distance < 300)  {
            // unbind to prevent excessive firing
            $(window).off('scroll', scrollProducts);
            console.log('we reached the bottom');

            $.ajax({
                type: 'GET',
                url: "foo/bar/2",
                success: function(data) {
                    console.log("success!");
                    $('#container').append(data).fadeIn();
                    // rebind after successful update
                    $(window).on('scroll', scrollProducts);
                }
            });
        }
    }
});
</script>

我想了解更新网址中页码的正确方法:foo/bar/2

我读到,由于同步和异步调用之间的差异,您不能使用全局变量,而是需要回调(尽管我无法理解它)。我还看到了一个解决方案,其中有人更新了隐藏字段的值,然后引用这些值,尽管这看起来是一个丑陋的解决方法。

在这种情况下处理页码的正确或推荐方法是什么,以便页码随着每次请求而增加,直到没有更多页面为止?

最佳答案

保留一个计数器并在您的请求中使用它

var page = 1;

$(document).ready(function() {
// see if we're at the bottom of the page to potentially load more content
$(window).on('scroll', scrollProducts);

function scrollProducts() {
    var end = $("#footer").offset().top;
    var viewEnd = $(window).scrollTop() + $(window).height();
    var distance = end - viewEnd;

    // when we're almost at the bottom
    if (distance < 300)  {
        // unbind to prevent excessive firing
        $(window).off('scroll', scrollProducts);
        console.log('we reached the bottom');

        $.ajax({
            type: 'GET',
            url: "foo/bar/" + page,
            success: function(data) {
                console.log("success!");
                $('#container').append(data).fadeIn();
                // rebind after successful update
                $(window).on('scroll', scrollProducts);
                page++;
            }
        });
    }
}
});

关于javascript - 如何使用 Jquery/Ajax 处理无限滚动的页码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50270018/

相关文章:

javascript - jQuery 函数扩展的范围问题

c# - 使用 jQuery AJAX 和处理程序 (ashx) 上传文件不起作用

java - 使用 ajax 和 Java servlet 读取输入

javascript - 顺时针旋转图标 360 度 angularjs

javascript - 如何跳出 while 循环和 if 语句?

jquery - float 操作菜单不适用于 Bootstrap CSS

javascript - 动态替换html标签

javascript - 使用alertify和ajax删除

javascript - 克隆音频对象

javascript - 使用 Javascript 进行编程梯度停止