2015-10-14 60 views
1

這可能很簡單,我試圖用AJAX/Javascript來做到這一點,但找不到一個好辦法。每隔一段時間從目錄加載圖片

我有這樣的代碼:

<?php 
$dir = "uploads/*"; 
foreach(glob($dir) as $file) 
{ 
echo '<img src="'.$file.'">'; 
} 
?> 

而且我希望圖像裝載在每一個之間的時間間隔。他們都是JPEG和相同的大小。

我想知道是否有一種方法來加載它們與setInterval和AJAX?或者把它全部保存在PHP中?

+1

有無PHP輸出圖像的URL的陣列。在客戶端,一個'setInterval()'函數可以一次選取一個數組項,使用'document.createElement()'構建一個圖像,並將其附加到當前存放上述代碼的任何容器中。 –

回答

0

我的解決辦法:

php接收所有文件一次通過ajax,然後使用setTimeout函數加載圖像每隔X秒。這個演示功能完全適用於4張圖片。

getImages.php

<?php 
echo json_encode(glob("upload/*")); 
?> 

images.html

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
 
<script> 
 
$(document).ready(function(){ 
 
    $.ajax({ 
 
     url: "http://888.com.de/stack/ajax_interval.php", 
 
     dataType: "json", 
 
     success: function(data){ 
 
      for(var i = 0; i < data.length; i++) { 
 
       (function(i) { 
 
        setTimeout(function() { 
 
         $("#holder").append("<p><img src='"+data[i]+"'</p>"); 
 
         }, 3000*i); //3000 = 3seconds 
 
        })(i); 
 
       }  
 
      }, 
 
     failure: function(errMsg) { 
 
      console.error("error:",errMsg); 
 
     } 
 
    }); 
 
}); 
 

 
</script> 
 
</head> 
 
<body> 
 
<div id="holder"></div> 
 
</body> 
 
</html>

+0

這工作完美!謝謝! –

+0

不客氣,很高興它解決了。 –

0

下面是一個可用於您的目的的JS文件的示例。這非常簡單 - 將ajax放入函數中,並使用5分鐘的setInterval()函數調用該函數。

$(document).ready(function(){ 

    setInterval(loadImages, 300000); //5 minutes 

    function loadImages() { 
     $("#images-container").load("/your_script.php"); 
    } 

}); 

如果你把它連同當前的PHP代碼 - 它應該載入它的輸出到DIV與id=images_container每5分鐘

1

我會設置你的PHP到功能可按像一個RESTful API端點。

而且就像您的問題所示,我可以使用jQuery的$.getJSON以及setInterval在您希望的任何時間段之後刷新圖像。

這裏是你如何能做到這一點(有很多,很多其他方式)
的一個實例:

PHP文件(GET-刷新imgs.php):

<?php 
$dir = "uploads/*"; 

echo json_encode(glob($dir)); 
?> 

JavaScript文件(AJAX -refresh.js):

$(function(){ 

    var intervalInMiliseconds = 10000; 

    //comment out if you don't want to load images immediately 
    refreshImgs(); 

    setInterval(function(){ 
    refreshImgs(); 
    }, intervalInMiliseconds); 

    function refreshImgs(){ 
    var container = $('body'); //use whatever container you wish. I'm using body. 

    $.getJSON('get-refresh-imgs.php', function(data){ 
     container.empty(); 
     data.forEach(function(el, indx, ary){ 
     container.append('<img src="' + el + '"/>'); 
     }); 
    }); 
    } 

}); 

然後,在你的HTML文件中包含的:

<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script> 
<script type="text/javascript" src="ajax-refresh.js"></script>