javascript - 无需刷新整个页面即可更新网页中的图像
问题描述
我是一名 JavaScript 初学者。我正在使用烧瓶将我的 python 代码与前端(plainJS、HTML 和 CSS)集成。
基本上,我在左侧有一个包含图像(或者更确切地说是图像的图块)的网页,在右侧有搜索结果。当用户选择图像中的特定图块时,它会被发送到后端进行处理,将结果(外观相似的图块)保存到文件夹中。这些将在网页的右侧自动检索。
这样做的问题是:当我运行烧瓶应用程序时,页面首先被加载,并且由于开头的结果文件夹包含上一个会话的图像,所以它们被加载了。此外,在 python 处理完成后,我必须手动刷新页面才能加载结果。
我尝试过:编写一个 setInterval 函数,每隔 5 秒更新一次图像的来源,这样当新结果到达时,它们可以自动显示。代码写在下面。显然这个函数根本不起作用(我输入了 console.log() 语句,但它们没有显示任何内容):
JAVASCRIPT--------->
setInterval(function(){
var images=document.getElementsByTagName('img');
for(var i=0;i<images.length;i++){
var dt=new Date();
console.log(dt); //does not display anything on the console
var img=images[i];
if(img.id!='MainIMAGE') // reload all images except image with id MainIMAGE
{
img.src=img.src+"?"+dt.getTime();
console.log(img.src); // does not display anything as well
}
}
},5000);
这是正确的解决方案吗?或者还有其他方法可以解决这个问题吗?
解决方案
您可以使用URL
来避免连接先前的time
参数:
setInterval(function() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
var dt = new Date();
console.log(dt); //does not display anything on the console
var img = images[i];
if (img.id != 'MainIMAGE') // reload all images except image with id MainIMAGE
{
const url = new URL(img.src);
url.search = 'time=' + dt.getTime();
img.src = url.href;
console.log(img.src + ' ' + dt); // does not display anything as well
}
}
}, 1000);
<img src="https://placeimg.com/200/200/any" />
推荐阅读
- php - 将 VBA 代码公式转换为 excel 可读公式
- python - 未插入 Bigquery 数据
- sockets - 我正在尝试创建简单的 flask_sockets 客户端服务器,但得到 404
- liquibase - 为条件索引生成的 Liquibase 代码在 MS SQL Server 中出现错误
- html - 当我在屏幕小于 450 像素时使用媒体查询时,如何在网格布局中对齐我的 div?
- angular - 如何在 Ionic 4 中使用自己的 cordova 插件
- javascript - Redux-thunk 调度功能在 Laravel 上不起作用
- spring - Spring with Quartz worker 只初始化一个成员一次?
- jmeter - 无法在 AWS 实例上进行主从设置。当我从 master 运行 jmeter 脚本时,我得到一个异常
- c++ - C++ - 智能指针 - 访问冲突读取位置 0xDDDDDDDD