Ajax调用以获取新数据

时间:2012-04-12 22:43:39

标签: php javascript jquery ajax

在下面的代码中,我希望以每次所有图像都有

的方式添加ajax调用

已经显示,Ajax将触发我的php查看/ images文件夹,看看是否有新文件。

如果有任何新文件,则应在下一个周期中添加并显示。

 <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 个答案:

答案 0 :(得分: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-function并对结果进行json编码:

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

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