javascript - 流中的 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);
解决方案
不要在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
推荐阅读
- android - 从 android 应用程序访问 facebook 页面时出现问题
- python - 如何在 python 中将时间添加到持续时间,而不是一天中的时间?
- kotlin - Kotlin 适配器模式:getter 函数上的方法名称重复错误
- azure-data-explorer - 如何在 Kusto 中查询具有空值和非空值的分组不同记录?
- pandas - HTTPError:HTTP 错误 404:未找到 TextBlob 和额外数据:第 1 行第 352 列(字符 351)(Phyton)
- windows-runtime - [winrt]无法初始化投影类型的基类
- python-3.x - 简化初始化方法 Python
- python - Python 十进制处理
- php - php pcre 正则表达式不带分隔符
- python - 签名交易的发件人无效 - 孟买多边形