0

好的,到目前为止,我有以下代码可以在我的“照片”目录中显示随机照片:

<html> 

<head> 
    <title>AWESOME Random Images</title> 

        <?php 
function randomimages(){ 
    $dirname = isset($_REQUEST['dir'])? $_REQUEST['dir'] : './photos/'; 
    $numimages = isset($_REQUEST['num'])? $_REQUEST['num'] : 20; 
    $pattern = '#\.(jpg|jpeg|png|gif|bmp)$#i'; 
    $files = array(); 
    if($handle = opendir($dirname)){ 
        while(($file = readdir($handle)) !== false){ 
            if(preg_match($pattern, $file)){ 
                array_push($files, "<center><img src='" . $dirname . $file . "' alt='' /></center>"); 
            } 
        } 
        closedir($handle); 
        shuffle($files); 
    } 
    return implode("<center><br/>", array_slice($files, 0, $numimages)) . "<br/></center>"; 
} 
?>

</head> 

我在目录中有 500 多张照片,我正在寻找一种方法来添加一个按钮,该按钮将在不重新加载页面的情况下显示额外的 20 张照片。如果这是可能的,我希望有人能指出我正确的方向。

4

3 回答 3

0

1-首先,您应该将您的操作代码放入<div>.

2-然后,您应该<div>使用 ajax 重新加载。为此,您应该编写一个 javascript 函数(在<script></script>

onclick3- 最后,在按钮的( onclick="functionname()")中写入 ajax 函数的名称


.load()方法可能对您有所帮助: http: //api.jquery.com/load/

于 2013-11-05T21:47:32.997 回答
0

好的......所以我有点了解 JQuery,这对我来说是最简单的。看看这个例子。它是自包含的。实际上,您可以随意命名 HTML 页面。确实需要调用另一个页面才能get_words.php使 ajax 工作。每次运行 ajax 时,它都会转储到 ajax,console.log()这样您就可以看到发生了什么。

show_words.html - 此页面是显示内容的页面。它以get_words.phphtml 格式和 json 格式进行 ajax 调用。

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>)

<style>
   table.word_list {border: 1px solid #C0C0C0; border-collapse:collapse; width:400px}
   table.word_list th, td {border: 1px solid #C0C0C0; margin:2px; padding-right:10px; 
                           padding-left:4px;}
</style>

<button id="more_words_table" type="button">More Words! (table)</button>&nbsp;&nbsp;&nbsp;
<button id="more_words_json"  type="button">More Words! (json)</button>&nbsp;&nbsp;&nbsp;
<div id="counter" style="display:inline-block"></div>

<table id="tbl_word_list" class='word_list'>
   <tr>
      <th style="width:30%">Word</th>
      <th>Meaning</th>
   </tr>
   <tbody>
   </tbody>
</table>

<script>

$(document).ready(function(){

   var word_count = 0; 
   var more_words = true; 

   $("#more_words_json").on("click",function(){ 
      if (more_words===false) return; 
      var request = 
         $.ajax({
               type: "POST",
               url:  "get_words.php",
               data:  { "offset" : word_count, "limit" : 5, "return" : "json"},
               dataType: "json"
            });

      request.done(function(data){ 
            console.log(data);
            if (data.length!==0) { 
               word_count+=5; 
               $.each(data, function(i,item){  
                  $("#tbl_word_list").append("<tr><td>"+item.word+"</td>"+
                                                 "<td>"+item.meaning+"</td></tr>");  
               }); 
               update_counter(); 
            }
            else { no_more_words(); }
         }); 
   });

   $("#more_words_table").on("click",function(){ 
      if (more_words===false) return; 
      var request = 
         $.ajax({
               type: "POST",
               url:  "get_words.php",
               data:  { "offset" : word_count, "limit" : 5, "return" : "table"},
               dataType: "html" 
            });

      request.done(function(data){
            console.log(data);
            if (data.length!==0) {
               word_count+=5; 
               $("#tbl_word_list").append(data);    
               update_counter(); 
            }
            else { no_more_words(); }
         }); 
   });

   function update_counter() {
      $("#counter").html(word_count+" words displayed"); 
   }

   function no_more_words() {
      more_words = false; 
      $("#counter").html("No more words available!");  
   }

}); 

</script>

get_words.php - 此页面获取一些$_POST值,然后打印一些数据,这些数据将由主页上的 ajax 调用检索。

<?php 

$word_list = array("Amorphous: indefinite, shapeless", "Beguile: deceive", "Caprice: impulse", "Cascade: steep waterfall", "Cashmere: fine, delicate wool", 
                     "Chrysalis: protective covering", "Cinnamon: an aromatic spice; its soft brown color", "Coalesce: unite, or fuse", 
                     "Crepuscular: dim, or twilit", "Crystalline: clear, or sparkling", "Desultory: half-hearted, meandering", "Diaphanous: gauzy", 
                     "Dulcet: sweet", "Ebullient: enthusiastic", "Effervescent: bubbly", "Elision: omission", "Enchanted: charmed", "Encompass: surround", 
                     "Enrapture: delighted", "Ephemeral: fleeting", "Epiphany: revelation", "Epitome: embodiment of the ideal", 
                     "Ethereal: celestial, unworldly, immaterial", "Etiquette: proper conduct", "Evanescent: fleeting", "Evocative: suggestive", 
                     "Exuberant: abundant, unrestrained, outsize", "Felicity: happiness, pleasantness", "Filament: thread, strand", "Halcyon: care-free", 
                     "Idyllic: contentedly pleasing", "Incorporeal: without form", "Incandescent: glowing, radiant, brilliant, zealous", 
                     "Ineffable: indescribable, unspeakable", "Inexorable: relentless", "Insouciance: nonchalance", "Iridescent: luster", 
                     "Languid: slow, listless", "Lassitude: fatigue", "Lilt: cheerful or buoyant song or movement", "Lithe: flexible, graceful", 
                     "Lullaby: soothing song", "Luminescence: dim chemical or organic light", "Mellifluous: smooth, sweet", 
                     "Mist: cloudy moisture, or similar literal or virtual obstacle", "Murmur: soothing sound", "Myriad: great number", 
                     "Nebulous: indistinct", "Opulent: ostentatious", "Penumbra: shade, shroud, fringe", "Plethora: abundance", "Quiescent: peaceful", 
                     "Quintessential: most purely representative or typical", "Radiant: glowing", "Redolent: aromatic, evocative", 
                     "Resonant: echoing, evocative", "Resplendent: shining", "Rhapsodic: intensely emotional", "Sapphire: rich, deep bluish purple", 
                     "Scintilla: trace", "Serendipitous: chance", "Serene: peaceful", "Somnolent: drowsy, sleep inducing", 
                     "Sonorous: loud, impressive, imposing", "Spherical: ball-like, globular", "Sublime: exalted, transcendent", 
                     "Succulent: juicy, tasty, rich", "Suffuse: flushed, full", "Susurration: whispering", "Symphony: harmonious assemblage", 
                     "Talisman: charm, magical device", "Tessellated: checkered in pattern", "Tranquility: peacefulness", "Vestige: trace", 
                     "Zenith: highest point",);  

$offset = (isset($_POST['offset'])) ? $_POST['offset'] : 0;
$limit  = (isset($_POST['limit']))  ? $_POST['limit']  : 5;
$return = (isset($_POST['return'])) ? $_POST['return'] : 'table';

// no more words... return empty json or nothing depending on the return type
if ($offset>=count($word_list)) 
{
   if ($return=="json") { print "[]"; }
   exit(); 
}

$subset = array_slice($word_list,$offset,$limit); 

if ($return == 'json')
{
   $data = array(); 
   foreach ($subset as $i => $item)
   {  
      list($word, $meaning) = explode(':',$item); 
      $data[] = array('word' => $word, 'meaning' => $meaning); 
   }
   print json_encode($data); 
}
else if ($return == 'table')
{  
   foreach ($subset as $i => $item)
   { 
      list($word, $meaning) = explode(':',$item);  
      print "<tr><td>{$word}</td><td>{$meaning}</td></tr>"; 
   } 
} 

?>
于 2013-11-05T23:17:37.690 回答
0

您可以使用 AJAX 动态加载新内容。使用 jQuery 库非常简单:

$.ajax({
    url: "http://example.com/images.php",
    done: function( data ) {
        if ( console && console.log ) {
            console.log(data);
        }
});

此代码将从http://example.com/images.phpurl 获取新数据并登录到控制台(您可以使用它做任何您想做的事情,例如生成 html 标签并插入 DOM。查看 jQuery 手册以获取更多示例http://api.jquery.com/jQuery。阿贾克斯

不要忘记准备这个新文件images.php以返回,例如数据。JSON. 此外,您还需要将一些变量传递给它,例如。喜欢您要加载的图像类别、限制或页码。

于 2013-11-05T21:33:29.533 回答