首页 > 解决方案 > 流中的 JavaScript GET 请求网页图像

问题描述

每次您访问该页面时,我都有一个带有新 jpeg 的网址。我想使用我的 javascript get 不断向该页面发送 get 语句并检索图像以将其显示在我的网页上,作为一个接一个容器中的图像“流”。目前我只能在运行该功能时获得第一张图像。我是 JavaScript 新手。

    isLive=true;
    let imageurl = SERVICE_URL;
    var ajaxImage = document.getElementById("liveImg");
      do {

            xhttp.open("GET",imageurl, true);
            xhttp.send();
            ajaxImage.src = imageurl;

          }
          while (isLive);

标签: javascriptrestloopsstreamjpeg

解决方案


不要在javascript中使用无限循环来做这样的ajax,因为它会发送许多请求而没有任何限制会使浏览器崩溃,是的,如果有很多客户端,服务器也会崩溃

相反,您需要的是一个计时器,例如每 5 秒更改一次图像

isLive=true;
let imageurl = SERVICE_URL;
var ajaxImage = document.getElementById("liveImg");
var timerKey = 0;

function Imgchanger{
    //incase you want to stop it just assign isLive=false somewhere
    if(!isLive){
        clearInterval(timerKey);
    }

    xhttp.open("GET",imageurl, true);
    xhttp.send();
    ajaxImage.src = imageurl;
}

timerKey  = setInterval(imgchanger, 5000); //5 seconds

推荐阅读