使用AJAX/jQuery刷新图像-->;image_feed.php代码


Using AJAX / jQuery to refresh an image --> image_feed.php code?

我正试图解决之前在stckoverflow上提出的一个问题——"使用AJAX/jQuery刷新图像"

使用AJAX/jQuery刷新图像

image_feed.php中的URL应该每次都会更改。但是,我不知道image_feed.php的代码应该是什么(甚至是一个例子)。有人能帮忙吗?

仅供参考,我的index.php是:

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
    var $img = $('#image1');
    setInterval(function() {
        $.get('image_feed.php?CAMERA_URI=<?=$camera_uri;?>', function(data) {
            var $loader = $(document.createElement('img'));
            $loader.one('load', function() {
                $img.attr('src', $loader.attr('src'));
            });
            $loader.attr('src', data);
            if($loader.complete) {
                $loader.trigger('load');
            }
        });
    }, 5000);
});
</script>
</head>
<body>
<div id="image1">
</div>
</body>

image_feed.php应该只返回图像的src作为响应。

<?php
// produce the src with your logic.
$src = "https://www.gravatar.com/avatar/daa6ae7c970d99c6c2b3a9d8895aaa1e?s=32&d=identicon&r=PG";
echo $src;

试试这个:

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script>
            $(document).ready(function() {
                var $img = $('#image1');
                setInterval(function() {
                    $img.attr('src', 'image_feed.php?CAMERA_URI=<?=$camera_uri;?>');
                }, 5000);
            });
        </script>   
    </head>
    <body>
        <img id="image1" src="image_feed.php?CAMERA_URI=<?=$camera_uri;?>">
    </body>
</html>

试试这个

$(function() {
  var $img = $('#image1');
  var loading = false;
  setInterval(function() {
    if ( loading === true ) {
      return;
    }
    loading = true;
    var image = new Image;
    image.src = <?php echo json_encode( "image_feed.php?CAMERA_URI=".urlencode( $camera_uri ) ); ?>;
    image.onload  = function() {
      loading = false;
      $img.attr("src",this.src);
    };
    image.onerror = function() {
      loading = false;
      // do something here
    };
  }, 5000);
});