Javascript 每当我的 json 数据文件更改时如何刷新页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37469178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:22:09  来源:igfitidea点击:

How to refresh a page whenever my json data file changes

javascriptjqueryjson

提问by Yogi

So I've got this local file named 'data.json' containing various data. I want to refresh my page only when some data in the json file changes. Appreciate your help if you can explain me with bit of code. I searched all over internet, I couldnt find appropriate answer.

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

回答by James Lawruk

Create a timer, fetch the json file every X milliseconds. If the json contents has changed since the last fetch, reload the page. The sample code below uses JQuery to fetch the json file, and checks every 2000 milliseconds. Be sure the json file contains valid json.

创建一个计时器,每 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>

回答by Yotam Salmon

Detecting a file change

检测文件更改

Well, first, you have to trigger an event or something when the file changes. Some information about that can be found here: Check if file has changed using HTML5 File API

(Copied from the link) Something like that should do the job:

好吧,首先,您必须在文件更改时触发事件或其他内容。可以在此处找到有关此的一些信息:使用 HTML5 文件 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);
        }
    }
})();

Refreshing the page

刷新页面

In this case, the your problem is with the refresh. Usually a page can be refreshed using location.reload(), but in your case, refreshing the page will lose the connection to the file (the user will have to re-select it in the file input)
If you want to update some data using the new file, just retrigger it, but I strongly recommend to not refresh the page.

However, if you do want to refresh the page entirely, you can make a kind of a "helper-app" (A background application that will read the file continously and via websocket notify the Javascript when the file has changed).

You can do something like that using Websocketsor $ajax(for jQuery) or XMLHttpRequest(non jQuery).

The helper app can be written in Java, C# or Python (C# for windows only) or any other language that HTTP server or Websocket server can be implemented in.

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

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

您可以使用Websockets$ajax(对于 jQuery)或XMLHttpRequest(非 jQuery)来做类似的事情。

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

回答by Brett84c

If you're using Node, it has a built-in fs.watch()function that basically checks to see if/when a file has changed. Otherwise, you'd likely want a setInterval to periodically get the JSON file via an AJAX call and update your variables/DOM. You could compare the old JSON object to the new one and if they're different, update the DOM/variables with the new data.

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

回答by Peter Darmis

You want to examine your json file in a very thorough way, in order to understand if it has changed. So what you should do is:

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

  • use jQuery getJSON()to load the initial data from your json file to a localStorage object.
  • 使用 jQuerygetJSON()将初始数据从 json 文件加载到 localStorage 对象。

then use jQuery getJSON()in a timed loop to get new data from your json file, compare them in-deep and very strict way with a little help from this awsome functionposted as an answer in a similar question here. If your localStorage objects, initial JSONand new JSONmatch Object.deepEquals(initialJSON, newJSON)then no change was made, if not then refresh the page.

然后getJSON()在定时循环中使用 jQuery从您的 json 文件中获取新数据,通过在类似问题here中作为答案发布的这个awsome函数的一点帮助,深入和非常严格地比较它们。如果您的 localStorage 对象,initial JSON并且new JSON匹配,Object.deepEquals(initialJSON, newJSON)则没有进行任何更改,如果没有,则刷新页面。

回答by codefreaK

Check this stackOverflow question and answer

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

If it's on the same server as your calling function you can use XMLHttpRequest-

This example is not asynchronous, but you can make it so if you wish.

检查这个stackOverflow问题和答案

是否可以使用 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

Ways to refresh Page Here are the first 20:

使用 javascript 或 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']()

So simply Combine two and two together you get what you want

所以简单地将两个和两个结合在一起,你就会得到你想要的

If you want to periodically check that

如果您想定期检查

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

参考日期比较示例 Mozilla

var

    nLastVisit = parseFloat(document.cookie.replace(/(?:(?:^|.*;)\s*last_modif\s*\=\s*([^;]*).*$)|^.*$/, "")),
    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!");
    }
}