如何在滚动时加载更多数据


How to load more data on scrolling

我有一个这样的容器:

<div class="row row-sm padder-lg ">
<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
...
</div></div>

内容由 php 页面上的此循环生成:

       <?php 
        foreach ($top->feed->entry as $key => $value) 
        {
            $value->title->label = str_ireplace( "- ".$value->artist->label, "",  $value->title->label);
            if($key >= $this->config->item("items_top"))
                return false;
            $image = $value->image[2]->label;
            if($image == '')
                $image = base_url()."assets/images/no-cover.png";
            $image = str_ireplace("170x170", "200x200", $image);
        ?>

"items_top"是要显示的最大图像的数组数量,如何在滚动时加载更多?因此,当用户在页面底部滚动时会自动加载新内容

更新

好的,我需要使用Ajax,但是该怎么做?在我的 php 中使用此代码是否正确?

    <script>
        $(document).scroll(function(e){
            // grab the scroll amount and the window height
            var scrollAmount = $(window).scrollTop();
            var documentHeight = $(document).height();
            // calculate the percentage the user has scrolled down the page
            var scrollPercent = (scrollAmount / documentHeight) * 100;
            if(scrollPercent > 50) {
                // run a function called doSomething
               doSomething();
            }
            function doSomething() {
                // do something when a user gets 50% of the way down my page
            }
        });
</script>   

简短的回答:你不能,至少不能用PHP。

由于 PHP 是在将页面提供给客户端之前在服务器端处理的,因此在收到页面后无法使用 PHP 对其进行编辑。这就是JavaScript或AJAX的工作。

如果将 PHP 脚本移动到包含在网站中的单独页面(最好是 php),则可以进行 AJAX 调用,在用户滚动后将部分 HTML 代码替换为脚本返回的内容。

此链接可能会帮助您:通过 ajax 将 DIV 内容加载为 HTML