2013-07-06 52 views
0

我在一个目录中有100多个图像,我使用下面的php代码生成一个页面,显示最新的图片。在一个页面中加载20个图像,加载同一目录下的所有图像

<?php 
function mtimecmp($a, $b) { 
    $mt_a = filemtime($a); 
    $mt_b = filemtime($b); 

    if ($mt_a == $mt_b) 
     return 0; 
    else if ($mt_a < $mt_b) 
     return -1; 
    else 
     return 1; 
} 

$images = glob($dirname."*.jpg"); 
usort($images, "mtimecmp"); 

for ($i = count($images) - 1; $i >= 0; $i--) { 
    $image = $images[$i]; 
    echo '<img src="'.$image.'" height ="400"/><br />'; 
} 

?>

我想要做的是产生一个新的页面(无论是在HTML或PHP)显示最后20页,然后给用户一个选项,以装载更多的图像。通过这种方式,当他们访问页面时,他们不必加载全部100多张图片,而只需加载20张。

感谢您的帮助。

+1

您正在寻找分页或AJAX请求!谷歌那些 –

回答

1

一般来说,任何涉及在加载后修改页面的任何事情都是用php以外的东西来完成的。我使用JavaScript,并为你想要做的,我会使用JQuery。用jQuery,它会是这个样子

<a id='load_twenty_button'>Load 20 more!</a> 
<div id='where_to_put_the_images'></div> 

<script> 
    var img_start = 20; 

    //when link is clicked, do the function 
    $('#load_twenty_button').click(function() { 
     var link = 'my_site/form_actions/getImages.php' 
     $.post(link 
     , { start: img_start 
      , end: img_start +20 
      } 
     , function (result) 
      { 
       //set the html of the div element to the html your php link return 
       $('#where_to_put_the_images').html(result); 
       img_start += 20; 
      } 
     ); 
    }); 
</script> 

然后你getIMages.php,使用$ _ POST [“开始”]和$ _POST [“端”]弄清楚在HTML中回音图像。任何echo'd都会发布到div元素'where_to_put_images'。如果您想在此之后再添加20个,您将不得不稍微工作一下,但这应该会让您有所收获。

此外,请确保链接JQuery。只需查看一个基本的JQuery示例,它将链接到顶部。

0

它真的很容易想到,仅仅只需要我的代码为refrence,您可以使用此array_slice功能

<?php 
    function mtimecmp($a, $b) { 
    $mt_a = filemtime($a); 
    $mt_b = filemtime($b); 

    if ($mt_a == $mt_b) { 
     return 0; 
    } 
    elseif ($mt_a < $mt_b) { 
     return -1; 
    } 
    return 1; 
    } 

    $images = glob($dirname."*.jpg"); 
    usort($images, "mtimecmp"); 

    $page = (isset($_GET["page"])) ? $_GET["page"] : 1; // current page 
    $offset = ($page * 20); // array_slice offset 
    $length = 20; // maximum images per page 
    $images = array_slice($images, -$offset, $length); // slice images array 

    if (!empty($images)) { 
    foreach($images as $image) { 
     echo '<img src="'.$image.'" height="400" /> '; 
    } 
    } 
?> 

和分页,HTML将看起来像这样的事情,它很简单的方法

<div> 
    <a href="?page=<?php echo ($page - 1); ?>">Prev</a> 
    <a href="?page=<?php echo ($page + 1); ?>">Next</a> 
</div>