我已经花了一整天但仍然无法弄清楚如何使用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更改为更大的数字。或许还有另一种方法可以做到这一点。谢谢。
答案 0 :(得分:0)
我认为你的东西有些混乱,JavaScript和PHP在两个不同的世界中运行 - 一个在客户端,一个在服务器端。
所以你不能直接&#34;从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>