重载& lt; img>元素来自同一来源

Reload <img> element from same source

本文关键字:lt img 重载 元素      更新时间:2023-09-26

我在URL http://192.168.1.53/html/cam.jpg上有一个图像(来自树莓派),这个图像变化非常快(它来自相机)。

所以我想在网站上使用一些JavaScript让它每秒重新加载这个图像。例如

我的HTML是:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Pi Viewer</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  </head>
  <body>
      <style>
          img,body {
              padding: 0px;
              margin: 0px;
          }
      </style>
      <img id="img" src="http://192.168.1.53/html/cam.jpg">
      <img id="img1" src="http://192.168.1.53/html/cam.jpg">
      <script src="script.js"></script>
  </body>
</html>

和我的脚本:

function update() {
    window.alert("aa");
    document.getElementById("img").src = "http://192.168.1.53/html/cam.jpg";
    document.getElementById("img1").src = "http://192.168.1.53/html/cam.jpg";
    setTimeout(update, 1000);
}
setTimeout(update, 1000);

alert正在工作,但图像没有改变:/(我有两个图像(它们是相同的))

问题是图像src没有改变,所以图像没有重新加载。

您需要说服浏览器该图像是新的。一个很好的技巧是在url后面附加一个时间戳,这样它总是被认为是新的。

function update() {
    var source = 'http://192.168.1.53/html/cam.jpg',
        timestamp = (new Date()).getTime(),
        newUrl = source + '?_=' + timestamp;
    document.getElementById("img").src = newUrl;
    document.getElementById("img1").src =  newUrl;
    setTimeout(update, 1000);
}
相关文章: