如何在滚动时加载更多数据
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 代码,包含用户滚动后脚本返回的内容。
这篇 link 可能会对您有所帮助:
Loading DIV content via ajax as HTML
我有这样一个容器:
<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 代码,包含用户滚动后脚本返回的内容。
这篇 link 可能会对您有所帮助: Loading DIV content via ajax as HTML