数据库
首页 > 数据库> > jQuery-使用带有MySQL数据库的无限滚动

jQuery-使用带有MySQL数据库的无限滚动

作者:互联网

我找到了一个很好的ajax / jquery无限滚动插件(http://hycus.com/2011/03/15/infinite-scrolling-like-new-twitter-with-php-mysql-jquery/),可以很好地适应我的内容,但是我遇到了一个问题-它只调用一次loadmore.php脚本.让我显示代码:

在我的index.php文件中:

<script type="text/javascript">
    $(window).scroll(function(){
        if($(window).scrollTop() == $(document).height() - $(window).height()){
            $('div#loadmoreajaxloader').show();
            $.ajax({
                url: "loadmore.php?lastid=" + $(".postitem:last").attr("id"),
                success: function(html){
                    if(html){
                        $("#postswrapper").append(html);
                        $('div#loadmoreajaxloader').hide();
                    }else{
                        $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
                    }
                }
            });
        }
    });
</script>

本节将调用我的loadmore.php文件,并向其发送上一则帖子的ID.这仅在我第一次滚动到页面底部时才有效,它从loadmore.php加载条目,但不会再次调用loadmore.php.我的loadmore.php文件具有以下代码:

<?php

include('./includes/config.php');

if($_GET['lastid']){
    $query = 'SELECT * FROM db WHERE id < "'.$_GET['lastid'].'" ORDER BY id DESC LIMIT 0,3';
    $result = mysql_query($query);
    while ($rec = mysql_fetch_object($result)) {

    [SET MY VARS]

    ?>

    [HTML & PHP DISPLAYING MY POST]

    <?php
    }
}

?>

在第一个ajax调用之后显示的3个帖子完美地出现了,正是我希望它们以正确的数据显示的方式.但是在出现前3个帖子之后,我无法显示接下来的3个帖子.

因此,如果我在index.php上默认有5个帖子,则滚动到底部,ajax调用另外3个帖子,它们将完美显示,但是此后没有任何显示,即使还有很多帖子需要显示.我的问题在哪里,ajax / jquery向导?

解决方法:

仅在您第一次滚动时才满足您的“如果”条件.因此,从本质上讲,将触发该事件,而不是当您滚动到页面底部时,而是在您开始滚动时.用以下代码替换您的代码:

<script type="text/javascript">
    var loading = false;

    $(window).scroll(function(){
        var h = $('#postswrapper').height();
        var st = $(window).scrollTop();

         // the following tests to check if 
         // 1. the scrollTop is at least at 70% of the height of the div, and 
         // 2. another request to the ajax is not already running and 
         // 3. the height of the div is at least 500. 
         // You may have to tweak these values to work for you. 
        if(st >= 0.7*h && !loading && h > 500){
            loading = true;
            $('div#loadmoreajaxloader').show();
            $.ajax({
                url: "loadmore.php?lastid=" + $(".postitem:last").attr("id"),
                success: function(html){
                    if(html){
                        $("#postswrapper").append(html);
                        $('div#loadmoreajaxloader').hide();
                    }else{
                        $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
                    }
                    loading = false;
                }
            });
        }
    });
</script>

标签:jquery,mysql,ajax,infinite-scroll
来源: https://codeday.me/bug/20191010/1883490.html