从json文件中读取最新值的JavaScript代码,该文件每隔几秒钟就会更新一次



我对JavaScript非常陌生,并试图将.json文件中的最新值显示到HTML页面中,该文件每10秒更新一次。我也每10秒读取一次文件,但我没有从文件中获得最新的值。我得到的值比我老50到60秒。

我尝试过禁用chrome中的浏览器cahche,但仍然存在相同的问题。有人能帮忙吗?

我读取json文件的JavaScript代码如下:

function readJsonFile(callback) {
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8080/PersonalProject/filename.json');
request.onload = function() {
if(request.status>=100 && request.status<=100) {
//perform some operation
callback(request.responseText);
}
else{
//perform some operation
callback('FAILED');
}
};
request.onerror = function() {
console.error('Connection error');
};
request.send();
}

setInterval(function(){
readJsonFile(function(stat){
console.log(stat);
});
}, 10000);

您可以在请求中添加时间戳作为参数,以避免导航器缓存:

...
let ms = Date.now();
request.open('GET', 'http://localhost:8080/PersonalProject/filename.json?ms' + ms);
...

当从html标头请求时,我随时需要更新js和css文件,并且它可以正常工作

最新更新