【问题标题】:How to handle page numbers for an infinite scroll with Jquery / Ajax?如何使用 Jquery / Ajax 处理无限滚动的页码?
【发布时间】:2018-05-10 09:46:30
【问题描述】:

这是我第一次尝试使用 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>

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

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

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

【问题讨论】:

    标签: javascript jquery ajax infinite-scroll


    【解决方案1】:

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

    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++;
                }
            });
        }
    }
    });
    

    【讨论】:

    • 嗯...现在我只是觉得很傻。我显然没有正确阅读this answer
    • 公平地说,我还发现您链接的线程中的问题和答案都有些复杂。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多