简体   繁体   English

无限 Ajax jQuery 错误在窗口滚动时加载更多(重复数据)问题

[英]Infinite Ajax jQuery bug where on window scroll it loads more (duplicates data) issue

I asked the question yesterday, I had good answers but it didn't solve my question to the best capabilities.我昨天问了这个问题,我有很好的答案,但它并没有以最佳能力解决我的问题。

To explain what's happening here, I am building a messaging system.. However!为了解释这里发生的事情,我正在构建一个消息传递系统..但是! When I load down it duplicates the post continuously and then randomly stops.当我加载它时,它会连续复制帖子,然后随机停止。 I'm not entirely sure why.我不完全确定为什么。 I've tried everything I know but it just isn't working.我已经尝试了我所知道的一切,但它只是不起作用。

$(document).ready(function() {

    var flag = 0;

    $.ajax({
        type: "GET",
        url: "assets/js/ajax/messages.php",
        data: {
            'offset': 0,
            'limit': 6,
            'user_id': <?php echo $User->Id(); ?>
        },
        success: function(data) {
            $('#messages').append(data);
            flag += 3;
        }
    });

    $(window).scroll(function() {
        if ($(window).scrollTop() >= $(document).height() - $(window).height()) {
            console.log('hi!'+ Date.now());
            $.ajax({
                type: "GET",
                url: "assets/js/ajax/messages.php",
                data: {
                    'offset': flag,
                    'limit': 3,
                    'user_id': <?php echo $User->Id(); ?>
                },
                success: function(data) {
                    $('#messages').append(data);
                    flag += 3;
                }
            });
        }
    });
});

Use Socket.io instead of ajax.使用 Socket.io 而不是 ajax。

But if you want to using this way, I suggest to append and checking the last message's id .但是如果你想使用这种方式,我建议附加并检查最后一条消息的 id 。

Then query new messages instead of query everything to avoid duplicates data.然后查询新消息而不是查询所有内容以避免重复数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM