【问题标题】:How to refresh a page whenever my json data file changes每当我的 json 数据文件更改时如何刷新页面
【发布时间】:2016-09-24 22:46:56
【问题描述】:

所以我得到了这个名为“data.json”的本地文件,其中包含各种数据。我只想在 json 文件中的某些数据发生更改时刷新我的页面。如果你能用一些代码解释我,感谢你的帮助。我在网上找遍了,我找不到合适的答案。

【问题讨论】:

  • 您的 json 文件中的数据是否会通过服务器端脚本进行更改?
  • 是的,彼得。他们是
  • 我知道这听起来很愚蠢,因为您已经有了答案,但是这里的功能是什么,您保留 json 的记录,好的,您可以随机或频繁地检查它?跨度>
  • @3yK 我希望我已经提供了你要找的所有东西

标签: javascript jquery json


【解决方案1】:

创建一个计时器,每 X 毫秒获取一次 json 文件。如果自上次获取后 json 内容发生了变化,请重新加载页面。下面的示例代码使用 JQuery 获取 json 文件,并每 2000 毫秒检查一次。确保 json 文件包含有效的 json。

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
    var previous = null;
    var current = null;
    setInterval(function() {
        $.getJSON("data.json", function(json) {
            current = JSON.stringify(json);            
            if (previous && current && previous !== current) {
                console.log('refresh');
                location.reload();
            }
            previous = current;
        });                       
    }, 2000);   
</script>
</html>

【讨论】:

  • 感谢这个例子,效果很好!有人可以详细解释 if 子句吗?如果json文件存在但有0个字节,我很难找出如何做同样的事情。我不仅想在 json 内容发生变化时重新加载,还想在 json 内容消失时重新加载。
【解决方案2】:

检测文件更改

嗯,首先,您必须在文件更改时触发一个事件或其他东西。可以在这里找到一些相关信息:Check if file has changed using HTML5 File API

(从链接复制)类似的东西应该可以完成这项工作:

(function() {
    var input;
    var lastMod;

    document.getElementById('btnStart').onclick = function() {
        startWatching();
    };
    function startWatching() {
        var file;

        if (typeof window.FileReader !== 'function') {
            display("The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('filename');
        if (!input) {
            display("Um, couldn't find the filename element.");
        }
        else if (!input.files) {
            display("This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            display("Please select a file before clicking 'Show Size'");
        }
        else {
            file = input.files[0];
            lastMod = file.lastModifiedDate;
            display("Last modified date: " + lastMod);
            display("Change the file");
            setInterval(tick, 250);
        }
    }

    function tick() {
        var file = input.files && input.files[0];
        if (file && lastMod && file.lastModifiedDate.getTime() !== lastMod.getTime()) {
            lastMod = file.lastModifiedDate;
            alert("File changed: " + lastMod);
        }
    }
})();

刷新页面

在这种情况下,您的问题在于刷新。通常可以使用location.reload() 刷新页面,但在您的情况下,刷新页面将失去与文件的连接(用户必须在文件输入中重新选择它)
如果您想使用新文件更新某些数据,只需重新触发即可,但我强烈建议不要刷新页面。

但是,如果您确实想完全刷新页面,您可以制作一种“帮助应用程序”(一个后台应用程序,它将持续读取文件并通过 websocket 在文件更改时通知 Javascript)。

您可以使用Websockets$ajax(用于jQuery)或XMLHttpRequest(非jQuery)来执行类似的操作。

辅助应用程序可以用 Java、C# 或 Python(C# 仅适用于 windows)或任何其他可以实现 HTTP 服务器或 Websocket 服务器的语言编写。

【讨论】:

    【解决方案3】:

    如果您使用的是 Node,它有一个内置的 fs.watch() 函数,基本上可以检查文件是否/何时更改。否则,您可能希望 setInterval 通过 AJAX 调用定期获取 JSON 文件并更新您的变量/DOM。您可以将旧的 JSON 对象与新的 JSON 对象进行比较,如果它们不同,请使用新数据更新 DOM/变量。

    【讨论】:

    • 您不需要节点来执行此操作,兄弟 http 请求响应标头提供了此类信息 ajax 请求响应标头可以解决问题help.dottoro.com/ljxsrgqe.php
    • 如果他们已经在使用 Node,那么 fs.watch() 将是最简单的方法,兄弟。并不是要暗示这是唯一的方法。
    • 好吧兄弟,我这么认为是我的错
    【解决方案4】:

    您想以非常彻底的方式检查您的 json 文件,以了解它是否已更改。 所以你应该做的是:

    • 使用 jQuery getJSON() 将初始数据从 json 文件加载到 localStorage 对象。

    然后在定时循环中使用 jQuery getJSON() 从您的 json 文件中获取新数据,在此 awsome function 的一些帮助下进行深入和非常严格的比较,该awsome function 在此处作为类似问题的答案发布。如果您的 localStorage 对象 initial JSONnew JSON 匹配 Object.deepEquals(initialJSON, newJSON) 则未进行任何更改,否则请刷新页面。

    【讨论】:

      【解决方案5】:

      检查这个 stackOverflow 问题和答案

      Is it possible to retrieve the last modified date of a file using Javascript?

      如果它与您的调用函数在同一台服务器上,您可以使用 XMLHttpRequest-

      This example is not asynchronous, but you can make it so if you wish.
      
      function fetchHeader(url, wch) {
          try {
              var req=new XMLHttpRequest();
              req.open("HEAD", url, false);
              req.send(null);
              if(req.status== 200){
                  return req.getResponseHeader(wch);
              }
              else return false;
          } catch(er) {
              return er.message;
          }
      } 
       alert(fetchHeader(location.href,'Last-Modified'));
      

      Refresh a page using javascript or html

      刷新页面的方法 以下是前 20 个:

      location = location
      location = location.href
      location = window.location
      location = self.location
      location = window.location.href
      location = self.location.href
      location = location['href']
      location = window['location']
      location = window['location'].href
      location = window['location']['href']
      location = window.location['href']
      location = self['location']
      location = self['location'].href
      location = self['location']['href']
      location = self.location['href']
      location.assign(location)
      location.replace(location)
      window.location.assign(location)
      window.location.replace(location)
      self.location.assign(location)
      and the last 10:
      
      self['location']['replace'](self.location['href'])
      location.reload()
      location['reload']()
      window.location.reload()
      window['location'].reload()
      window.location['reload']()
      window['location']['reload']()
      self.location.reload()
      self['location'].reload()
      self.location['reload']()
      self['location']['reload']()
      

      因此,只需将两个和两个组合在一起即可获得所需的内容

      如果你想定期检查

      setInterval(function(){ 
      //the function here 
      and compare and update last_mod_date var if there changes else keep it like that
      
      }, 3000);
      

      Reference date comparison Example Mozilla

      var
      
          nLastVisit = parseFloat(document.cookie.replace(/(?:(?:^|.*;)\s*last_modif\s*\=\s*([^;]*).*$)|^.*$/, "$1")),
          nLastModif = Date.parse(document.lastModified);
      
      if (isNaN(nLastVisit) || nLastModif > nLastVisit) {
          document.cookie = "last_modif=" + Date.now() + "; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=" + location.pathname;
          if (isFinite(nLastVisit)) {
              alert("This page has been changed!");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-31
        • 1970-01-01
        • 2018-06-05
        • 2011-06-05
        • 1970-01-01
        相关资源
        最近更新 更多