我已经花了一整天,但仍然无法弄清楚如何使用jquery加载更多按钮,这将更改我的php脚本中变量的值,启动我的for循环并从我的照片文件夹中加载更多照片。我的 Jquery 脚本是:
$(document).ready(function() {
$("button").click(function(){
$("php").attr({
"$b" : "16"
});
});
});
我的php代码是:
$charnum = strlen($file);
$b = 8;
$directory = "resource/galery/";
if (is_dir($directory)) {
if ($dh = opendir($directory)) {
for ($i = 0; ($file = readdir($dh)) && $i < $b; ++$i) {
if($file !="." && $file!=".."){
echo '
<div class="img">
<a target="_blank" href="/resource/galery/'.$file.'">
<img class="img-responsive" src="/resource/galery/'.$file.'">
</a>
<div class="desc">'.substr($file, 0, $charnum - 4).'</div>
</div>';
}
}
closedir($dh);
}
}
我想将$b从 8 更改为更大的数字。或者也许还有另一种方法可以做到这一点。谢谢。
我认为你把事情搞混了,JavaScript 和 PHP 在两个不同的世界中运行 - 一个在客户端,一个在服务器端。
所以你不能"直接"从JavaScript中更改变量。你必须通过HTTP请求(如GET或POST请求)传递变量来做到这一点,然后PHP脚本将呈现一个可以在JavaScript中访问的响应。
下面是一个可能的分页解决方案:
.JS:
$(document).ready(function() {
$("button").click(function(){
// try to get current page, or start off with 0 and increment by one.
var page = (parseInt($(this).data('page')) || 0) + 1;
// save current page as data state on the button
$(this).data('page', page);
// we call the PHP script and pass a GET variable which indicates
// which page we want to load.
$.get('yourphpscript.php?'+ $.param({page: page}), function(data) {
// append the result from your PHP script to #result element
$('#result').append(data);
});
});
});
PHP (yourphpscript.php):
// 8 images per page
$perPage = 8;
// sanitize page to be a number, default to 0 - the "first page"
$page = intval(is_numeric($_GET['page']) ? $_GET['page'] : 0);
$charnum = strlen($file);
$directory = "resource/galery/";
if (is_dir($directory)) {
if ($dh = opendir($directory)) {
// loop up to and including the requested page
for ($i = 0; ($file = readdir($dh)) && ($i % $perPage) <= $page; ++$i) {
// only output if we are on the requested page
if($file !="." && $file!=".." && ($i % $perPage) == $page) {
echo '
<div class="img">
<a target="_blank" href="/resource/galery/'.$file.'">
<img class="img-responsive" src="/resource/galery/'.$file.'">
</a>
<div class="desc">'.substr($file, 0, $charnum - 4).'</div>
</div>';
}
}
closedir($dh);
}
}
.HTML:
<div id="result">
<!-- images go here -->
</div>
<button type="button">Load more</button>