2016-03-20 27 views
0

我花了整整一天的时间,但仍然无法弄清楚如何使用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); 
    } 
} 

我想从8更改$ B到更大的数字。或者也许有另一种方式来做到这一点。谢谢。

+0

你能还包括你用来请求PHP的jQuery代码请。 –

+0

这是你在找什么http://stackoverflow.com/questions/15774669/list-all-files-in-one-directory-php? – Undefitied

+0

你是否认为你的jQuery代码将修改它加载的同一页面的PHP? PHP是服务器端,一旦用户看到页面就完成了。如果您想再次使用PHP,则需要使用Ajax并对PHP页面进行额外的调用。 – ThrowBackDewd

回答

0

我认为你的东西有点混乱,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> 
+0

它不工作,因为我所有的JS,HTML和PHP存储在一个单一的文件。 –