我有一个 Django 网页,它基本上显示了一些基于某些分析的图表。此分析可能持续超过 10 分钟,在此期间用户可以按网页上的刷新按钮来刷新图形。因此在后端目录中的图形(图像)被新图形覆盖(路径和图像名称保持不变)。但是当我按下浏览器刷新按钮而不是当我点击我的网页上的刷新按钮时,这会反射(reflect)出来,即使两个地方使用的代码都是彼此的副本。
我的 onload
函数 ID 称为 getGraphs()
。每次点击浏览器刷新按钮重新加载页面时,都会调用此函数,代码如下,
function getGraphs(ip)
{
$.ajax({
url: '/getGraphs/',
type: 'GET',
data: {"ip":ip},
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (result) {
$('#res').empty(); //div I am updating
resDiv = document.getElementById("res");
var data = result.data["directory"];
for (var i = 0; i < data.length; i++)
{
resDiv.innerHTML+=('<h2>'+data[i]["name"]+'</h2>');
var images = data[i]["images"];
for (var j = 0; j < images.length; j++) {
console.log("i:"+i+" dataLen:"+images.length)
var path="results/"+result.uniqueID+"/"+data[i]["name"]+"/"+images[j]["name"]; //the path of the image
resDiv.innerHTML+=("{% load static %}<img class='hoverImages' onclick=\"zoomIn('"+path+"')\" style='width:600px;height:300px;' src=\"{%static '"+path+"'%}\"/>    ");
}
}
},
error: function (){
alert("error from getting dir");
}
});
}
对于网页上的刷新按钮,我有两个版本的刷新按钮代码。
版本 1(这基本上调用了 onload 函数并更新了图表):
function refresh()
{
location.reload();
}
版本 2(我在 onload 函数中的确切代码,但图表未更新):
function refresh(ip)
{
$.ajax({
url: '/getGraphs/',
type: 'GET',
data: {'ip':ip},
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (result) {
$('#res').empty();
resDiv = document.getElementById("res");
var data = result.data["directory"];
for (var i = 0; i < data.length; i++)
{
resDiv.innerHTML+=('<h2>'+data[i]["name"]+'</h2>');
var images = data[i]["images"];
for (var j = 0; j < images.length; j++) {
var path="results/"+result.uniqueID+"/"+data[i]["name"]+"/"+images[j]["name"];
resDiv.innerHTML+=("{% load static %}<img class='hoverImages' onclick=\"zoomIn('"+path+"')\" style='width:600px;height:300px;' src=\"{%static '"+path+"'%}\"/>    ");
}
}
},
error: function (){
alert("Error refresh!")
}
});
}
HTML 代码(已编辑):
对于版本 1:
<button id="refresh" onclick="refresh()" style="position:relative;display: inline-block;width:11vh;" class="btn btn-primary">REFRESH</button>
对于版本 2:
<button id="refresh" onclick="refresh('{{ip}}')" style="position:relative;display: inline-block;width:11vh;" class="btn btn-primary">REFRESH</button>
我对自己做错了什么感到很困惑,因此需要指导。
提前致谢。
最佳答案
问题很可能是这样的:
So in the backend the graphs(images) in the directory are overwritten with new graphs(the paths and image names remain the same).
当您动态更新 DOM 时,浏览器可能足够聪明,不会下载相同的图像两次。
您可以做的是通过将随机查询字符串附加到 url 来尝试“使”图像“无效”。
var path = "results/.../..."
path += "?" + Math.random()
关于javascript - 通过 onload() 和刷新按钮刷新网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40778686/