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

时间:2013-07-15 06:13:31

标签: php ajax

我正在尝试解决先前在stckoverflow上提出的问题 - “使用AJAX / jQuery刷新图像”

Using AJAX / jQuery to refresh an image

来自image_feed.php的网址应该每次都改变。但是,我无法弄清楚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>

3 个答案:

答案 0 :(得分:1)

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;

答案 1 :(得分:0)

试试这个:

<!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>

答案 2 :(得分:0)

试试这个

$(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);
});