每当我的json数据文件发生更改时如何刷新页面 [英] How to refresh a page whenever my json data file changes

查看:246
本文介绍了每当我的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>

这篇关于每当我的json数据文件发生更改时如何刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆