2012-04-12 71 views
0

在下面的代码我想在某种程度上增加一个Ajax调用,每次,毕竟图像有Ajax调用来获取新的数据

被证明,阿贾克斯将触发我的PHP寻找到了/图片查看是否有新文件。

如果有任何新文件,应在下一个循环中添加并显示它们。

<html> 
<meta http-equiv="refresh" content="1000"/> 
<head> 
<title>Slideshow</title> 
<style type="text/css"> 
    #slideshow 
    #slideshow img { padding: 15px; border: 1px solid #ccc; background-color: #eee; } 
    #slide {width: 370px; height: 220px; padding: 0; margin: 0 auto; } 

    #myslides { 
    width: 370px; 
    height: 220px; 
    padding: 0; 
    margin: 0 auto; 
} 

#myslides img { 
    padding: 10px; 
    border: 1px solid rgb(100,100,100); 
    background-color: rgb(230,230,230); 
    width: 350px; 
    height: 200px; 
    top: 0; 
    left: 0 
} 

</style> 
</head> 
<!-- include jQuery library --> 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> 

<!-- include Cycle plugin --> 
<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js"></script> 

<script type="text/javascript"> 
$(document).ready(function(){ 
$('#slideshow').cycle({ 
       fx: 'fade', 
       speed: 700, 
       timeout: 8000 
     }); 
}); 
</script> 

<body> 

<div id="slideshow"> 

<?php 

    function returnimages($dirname="./images") { 
     $pattern="([^\s]+(\.(?i)(jpg|png|gif|bmp))$)";  
     $files = array(); 
     if($handle = opendir($dirname)) { 
      while(false !== ($file = readdir($handle))){ 
       if(preg_match($pattern, $file)){ //if this file is a valid image 
        $files[] = $file; 
       } 
      } 

      closedir($handle); 
     } 
     //sort($files);   
     natcasesort($files); 

     return($files); 
    } 

    $images = returnimages(); //will get the array containing the images 
    foreach($images as $img) 
    { 
     echo '<img src="images/' . $img . '" />'; 
    } 
?> 

</body> 
+1

不错。开始阅读http://api.jquery.com/category/ajax/ – Michelle 2012-04-12 22:50:12

+0

这非常有帮助。 – user1325414 2012-04-12 23:07:05

+0

jQuery Cycle在结尾处没有事件,所以它似乎需要某种破解或扩展才能实现。 ajax调用本身很容易,只需在幻灯片ID和页面上使用一个负载即可。 – 2012-04-12 23:15:04

回答

0

添加JavaScript到您的页脚与某些intervalls发送新图像的请求:

<script> 
    $(function(){ 
     setIntervall("fetchImages()", 20000); 

     function fetchImages() { 
      $.ajax({ 
       type: "GET", 
       url: "yourImageFetchingScript.php" 
      }).done(function(response){ 
       var curImgCount = $('#slideshow img').length; 
       if (response.length > curImgCount) { 
        for (var i = curImgCount; i < response.length; i++) { 
         $('#slideshow').append('<img src="images/' + response[i] + '"');  
        } 
       } 
      }); 
     } 
    }); 
</script> 

然后yourImageFetchingScript.php可能只是打电话给你returnimages功能和JSON编码的结果:

$images = returnimages(); 
echo json_encode($images); 

查看jQuery的ajax documentation了解更多详情。

+0

Oppps ...错过了你的周期。使用一些甚至由循环触发的调用fetchImage而不是setIntervall函数。 – p3n0l 2012-04-12 23:52:39

+0

你能更清楚吗? – user1325414 2012-04-13 01:14:44