How to refresh a page whenever my json data file changes

前端 未结 5 447
甜味超标
甜味超标 2020-12-29 14:26

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

相关标签:
5条回答
  • 2020-12-29 14:42

    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>
    
    0 讨论(0)
  • 2020-12-29 14:46

    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:

    • use jQuery getJSON() to load the initial data from your json file to a localStorage object.

    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 function posted as an answer in a similar question here. If your localStorage objects, initial JSON and new JSON match Object.deepEquals(initialJSON, newJSON) then no change was made, if not then refresh the page.

    0 讨论(0)
  • 2020-12-29 15:02

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

    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

    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!");
        }
    }
    
    0 讨论(0)
  • 2020-12-29 15:03

    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.

    0 讨论(0)
  • 2020-12-29 15:08

    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:

    (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 Websockets or $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.

    0 讨论(0)
提交回复
热议问题