我有这个脚本,它在用户到达页面末尾时发出 ajax 请求。它基于滚动事件。在页面加载时,我在用户屏幕上只显示 16 种产品,当他向下滚动时,我希望加载另外 16 种产品。我的脚本正在运行,但它执行了多个 ajax 请求,这不是我想要的。这个想法只是为了展示另一组 16 种产品。脚本是:
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $('.made').offset().top) {
//here I count how many products I have shown already
var productsshown = $(".productcell").length;
$('.made').hide();
$.ajax({
type: "post",
url: "./ajax/get_more_products.php",
data: {
"product": productsshown
},
dataType: 'json',
cache: false,
success: function(data) {
$("#bcontent").html(data);
$('.made').show();
}
});
}
});
如您所见,我有一个用作 Controller 的 div,当用户看到此 div 时 - 正在执行 ajax。来自 ajax 的结果被加载到另一个带有 id="content"
如何避免 scroll 事件多次执行 ajax 调用?我尝试通过隐藏我的 Controller div .made 并在 ajax 响应时再次显示它,以便当用户再次访问它时它可以为另外 16 种产品执行。但是 ajax 总是被调用多次执行,因为我想要它。 .
最佳答案
嗯,这是对你的代码的一个小补充,添加一个标志,每当你加载更多项目时切换:
var _itemsLoading = false;
if ((!_itemsLoading) && ($(window).scrollTop() + $(window).height() > $('.made').offset().top)) {
//here I count how many products I have shown already
var productsshown = $(".productcell").length;
$('.made').hide();
_itemsLoading = true;
$.ajax({
type: "post",
url: "./ajax/get_more_products.php",
data: {
"product": productsshown
},
dataType: 'json',
cache: false,
success: function(data) {
$("#bcontent").html(data);
$('.made').show();
_itemsLoading = false;
}
});
}
关于javascript - 当 html 元素在用户屏幕上可见时执行 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30168068/