javascript - 当 html 元素在用户屏幕上可见时执行 ajax

标签 javascript jquery html ajax

我有这个脚本,它在用户到达页面末尾时发出 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"

的 div 中

如何避免 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/

相关文章:

javascript - 响应式视频浏览器不稳定,Safari 除外

javascript - Javascript 对象属性的引用错误

javascript - 在javascript中使用this获取未定义的设置对象的属性值

Javascript/JQuery 忽略更改事件的 stopPropagation

javascript - [HTML][Javascript][Canvas] 无法使多边形函数工作

javascript - 始终启用 ng-disabled 的按钮

javascript - 悬停时自动播放 html 视频?

javascript - 如何每 5 秒加载一次 div 内的内容?

javascript - 有没有办法在应用后从元素中删除 fitVids() ?

javascript - 我如何更好地重新排序我的 javascript 代码?