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

JavaScript code to read the latest values from a json file that keeps getting updated every few seconds

我是 JavaScript 的新手,我正在尝试将 .json 文件中的最新值显示到 HTML 页面中,该文件每 10 秒更新一次。我也每 10 秒读取一次文件,但我没有从文件中获取最新值。我得到的值早了 50 到 60 秒。

我已尝试在 chrome 中禁用浏览器缓存,但问题仍然存在。有人可以帮忙吗?

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

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);
...

每当我需要更新 js 和 css 文件时,我都会在 html header 请求时这样做,并且它有效