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

问题描述:

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

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.

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

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.

<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>