从同一来源重新加载<img>元素

Mar*_*mko 2 html javascript image

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

所以我希望在网站上有一些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>
Run Code Online (Sandbox Code Playgroud)

我的剧本:

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);
Run Code Online (Sandbox Code Playgroud)

警报正在工作,但图像没有变化:/(我有2张图片(它们是相同的))

Gab*_*oli 10

问题是图像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);
}
Run Code Online (Sandbox Code Playgroud)