JavaScript method to import a local JSON file every x minutes

I am new to JavaScript and I was looking for a solution to this problem:

I have names and numbers that are written to the data.json file in the same directory as in my JavaScript file. I am looking for a few minutes to verify that data.json and update the HTML p tag with the changes.

My HTML block is as follows:

...
<body>
  <p id="mydata">
  </p>
</body>
...

My data.json look like this:

[{"Name":"Charlie","Number":"5"},{"Name":"Patrick","Number":"3"}]

My Javascript block looks like this:

...
setInterval(function(){
    var json = // read in json file
    //this is the part I'm missing
    document.getElementById('mydata').innerHTML = json;
},300000); // every 5 minutes
+6
source share
2 answers

$. getJSON will load the local json file

setInterval(function(){
    $.getJSON("yourjsonfile.json", function(json) {
        console.log(json); 
        document.getElementById('mydata').innerHTML = json;
    });
},300000); // every 5 minutes
+2
source

Make sure of two things:

  • You String Object JSON
  • ,

, , , :

var counter = 0;
setInterval(function(){
counter++;
    var json = JSON.stringify([{"Name":"Charlie","Number":"5"},{"Name":"Patrick","Number":"3"}]);
    document.getElementById('mydata').innerHTML = counter + json;
},1000);
<p id="mydata">
</p>
Hide result
0

All Articles