gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:03:55 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com