Javascript 不会在浏览器中更新文档

Javascript doesn't update document in browser

本文关键字:更新 文档 浏览器 Javascript      更新时间:2023-09-26

我的服务器目录中有一个data.json。我正在使用 w3school 的以下代码在浏览器中显示数据。W3学校片段链接

<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "/static/data.json", true);
  xhttp.send();
}
</script>
</html>

当我单击该按钮时,我可以在我的网页中看到data.json。但是当我更改 data.json 并再次单击按钮(不刷新页面)时,更新的数据不会显示在浏览器中。

我在这里错过了什么吗?

既然你使用的是XMLHttpRequest,你需要确保每个请求都是唯一的,你可以做这样的事情:

var uniqueId = (new Date()).getTime()
xhttp.open("GET", "/static/data.json?debug=" + uniqueId, true);

如果你使用的是jQuery ajax(http://api.jquery.com/jquery.ajax/),你只需要传递cache=false,像这样:

$.ajax({
  cache: false,
  //other options...
});
   xhttp.open("GET", "/static/data.json?something=RANDOMGUID", true);