I have a JSON like what you see below, that I want to “keep alive”. I would like to continually query the server (“refresh” at a continual interval, say 30 seconds) and update what’s displayed on the page accordingly. The JSON appears as so:
[
{
"Name": "Paul",
"Date": "2012-10-26",
"Score": 8
},
{
"Name": "Janet",
"Date": "2012-10-24",
"Score": 18
},
{
"Name": "Rick",
"Date": "2012-10-26",
"Score": 13
}
]
My current (static) version to display this is:
<body>
<script>
$.getJSON('myjson.json', function(data) {
for (var i in data) {
var Name = data[i].Name;
var Score = data[i].Score;
}
var output = "<ul>";
for (var i in data) {
output += "<li>" + Name + "--" + Score;
}
output += "</ul>";
document.getElementById("placeholder").innerHTML=output;
});
</script>
<div id="placeholder"></div>
</body>
This of course displays the data, but how would I “stream” the changes to “Score” as the json changes on the server (without refreshing the page)?
Is this what’s referred to as polling?
Any help is appreciated. Thank you
You just need to use a timer, or to be more specific,
setInterval()…The above script will run the
getData()function at document.ready and then every 30 seconds, and update the#placeholderelement with the return value.