如何在不刷新整个页面的情况下在后台刷新相机的图像


How to refresh image from camera in background without refreshing whole page?

我正在使用PHP脚本(currentimage.PHP)从我的CCTV IP摄像机获取快照,它运行良好:

<?php
while (@ob_end_clean()); 
    header('Content-type: image/jpeg'); 
// create curl resource 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_USERAGENT, $useragent); 
curl_setopt($ch, CURLOPT_URL, 'http://192.168.0.20/Streaming/channels/1/picture'); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_USERPWD, 'username:password'); 
// $output contains the output string 
$output = curl_exec($ch); 
echo $output; 
// close curl resource to free up system resources 
curl_close($ch);
?>

和另一个显示数据的PHP/HTML:

<IMG id="myImage" SRC='currentimage.php'>

但我不能让它每30秒刷新一次背景图像。我正在尝试AJAX,但没有成功:

<script>
      function refresh_image(){
          document.getElementbyId("myImage").setAttribute("src", "currentimage.php");
        }
        setInterval(function(){refresh_image()}, 30000);
</script>

我做错了什么?我将感谢任何帮助

我尝试过通过对PHP脚本的定时请求来更改显示图像的概念,它运行良好。如果URL被修改,就会向图像获取脚本发出一个新的请求,我通过在URL中添加一个版本号作为参数来实现这一点。

var version = 1;
function refresh_image(){
  document.getElementById("myImage").setAttribute("src", "currentimage.php?ver="+version);
  version++;
}
setInterval(function(){
  refresh_image();
}, 2000);

我怀疑这里的主要问题是浏览器缓存了你的文件,如果你再次设置属性,它将不会重新加载。不过,我已经找到了解决这个问题的方法:

document.getElementbyId("myImage").setAttribute("src", "currentimage.php?version=1");

保存版本号,并在每次提出请求时进行计数。这样,浏览器会将其视为一个新的URL,并将再次重新加载(请使用网络选项卡中浏览器的开发人员功能进行检查)。