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.
相关问题
- Is there a limit to how many levels you can nest i
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- How to toggle on Order in ReactJS
- StackExchange API - Deserialize Date in JSON Respo
If you want to periodically check that
Reference date comparison Example Mozilla
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:
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.
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:
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
andnew JSON
matchObject.deepEquals(initialJSON, newJSON)
then no change was made, if not then refresh the page.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.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.