首页 > 解决方案 > 无需刷新整个页面即可更新网页中的图像

问题描述

我是一名 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);

这是正确的解决方案吗?或者还有其他方法可以解决这个问题吗?

标签: javascriptflask

解决方案


您可以使用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" />


推荐阅读