微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐