【发布时间】: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