在php应用程序中自动刷新图像

时间:2016-03-14 00:14:26

标签: javascript php jquery ajax

我一直在用PHP编写一些rest应用程序。应用程序通过REST从服务器下载映像并返回html代码以将其添加到网页。这是php代码的一个示例(images.php文件):

include 'Camera.php';
include 'Image.php';
include 'httpful.phar';
$c = new Camera();//new  Camera object
$c ->getCameras();//get array of all cameras
$img = new Image(); //new Image object
$n = count(Camera::$cameralist); //lenght of array 

for ($index = 0; $index < $n; $index++) {
echo '<img id="refresh" src="' . $img->getImage($index) . '">'; //show all images
} 

index.php文件是主页文件。它可以显示图像并每隔5秒刷新一次。我做了一半的工作。图片显示。但是,如果我想使用javascript刷新它,这只刷新php代码而不是我能看到的图像。

<html>
    <head>
        <meta charset="UTF-8">
        <title>Camera Service</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
        <div id="refresh">  


    </div>
    </body>
    <script type="text/javascript">
  setInterval("moja_funkcja();",5000); 
    function moja_funkcja(){
      $('#refresh').load('images.php');
    }

    </script>
</html>

此代码有哪些变化?我希望它会起作用 提前致谢

1 个答案:

答案 0 :(得分:3)

一种可能的解决方案是获取所有图片网址(src属性)一次,然后通过附加时间戳来更新图片网址,即

<img src="/camera1.jpg">

将成为

<img src="/camera1.jpg?t=1457915755"> <img src="/camera1.jpg?t=1457915760">

等等,浏览器将重新加载图像。我随意选择参数名称“t”,你可以随意命名。

使用服务器端的Cache-Control传送图像有更好的方法,请查看以下答案:Upspin's concept of an operational trace

<html>
    <head>
        <meta charset="UTF-8">
        <title>Camera Service</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

        <script type="text/javascript">
          $(function() {
            // load images initially to get the "src" attribute
            $('#refresh').load('images.php', function() {
              // images loaded
              $('#refresh').find('img').each(function() {
                // store original src attribute
                $(this).data('original-src', $(this).attr('src'));
              });

              // every 5 seconds, update the src with a new timestamp
              setInterval(function() {
                $('#refresh').find('img').each(function() {
                  var src = $(this).data('original-src');
                  // if there's already a query string we need to append with &
                  src += (src.indexOf("?") === -1) ? '?' : '&';
                  // our parameter is named "t", this will change with time,
                  // so the browser will reload the image.
                  src += 't=' + new Date().getTime();
                  // update the image src
                  $(this).attr('src', src);
                })
              },5000); 
            }) 
          });
        </script>
    </head>
    <body>
        <div id="refresh"></div> 
    </body>
</html>

如果您只需要刷新内容,即重新获取PHP脚本 - 这变得更加简单,您只需将时间戳附加到PHP脚本的URL:

<html>
    <head>
        <meta charset="UTF-8">
        <title>Camera Service</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

        <script type="text/javascript">
          function loadImages() {
            $('#refresh').load('images.php?' + new Date().getTime(), function() {
              // call "recursively" once fetched
              setTimeout(loadImages, 5000);
            }); 
          };

          // trigger first fetch once page is loaded
          $(function() {
            loadImages();
          });
        </script>
    </head>
    <body>
        <div id="refresh"></div> 
    </body>
</html>

第三个选项,如果您只想刷新PHP脚本的输出,则禁用服务器和客户端的缓存,因此您不必使用URL:

PHP:

include 'Camera.php';
include 'Image.php';
include 'httpful.phar';

$c = new Camera();//new  Camera object
$c ->getCameras();//get array of all cameras
$img = new Image(); //new Image object
$n = count(Camera::$cameralist); //lenght of array 

// this must happen before you output any content
header("cache-control: no-cache");

for ($index = 0; $index < $n; $index++) {
echo '<img id="refresh" src="' . $img->getImage($index) . '">'; //show all images
} 

HTML:

<html>
    <head>
        <meta charset="UTF-8">
        <title>Camera Service</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

        <script type="text/javascript">
          function loadImages() {
            $.ajax({
                url: "images.php",
                cache: false, // disables caching!
                dataType: "html",
                success: function(data) {
                    $("#refresh").html(data);
                    setTimeout(loadImages, 5000);
                }
            });
          };

          // trigger first fetch once page is loaded
          $(function() {
            loadImages();
          });
        </script>
    </head>
    <body>
        <div id="refresh"></div> 
    </body>
</html>