Reputation: 5770
I am trying to figure out how to update a ul li list live.
So lets say: we have a unordered list, and each li element is displayed newest to oldest. I am looking for a method, to poll the server for an update, and push that update to the list ( presumably using jSon ) live and without refreshing page.
Example.
<ul>
<li>12 seconds ago: Apple</li>
<li>32 seconds ago: Banana</li>
<li>42 seconds ago: Grape</li>
</ul>
<ul>
<li>2 seconds ago: Pineapple</li>
<li>22 seconds ago: Apple</li>
<li>32 seconds ago: Banana</li>
<li>52 seconds ago: Grape</li>
</ul>
So if we just stare at the page, like a sad loser. The list automatically uploads, every x seconds, with latest data from the server.
I would just like some pointers as to what to look for for this kind of thing, and really what it is we should be looking for.
Not sure if pushing data from the server is a better method than pulling data from the server, I would imagine push would reduce overload.
Any sugegstions would be gratly appreciated.
Upvotes: 0
Views: 74
Reputation: 11
There's actually a SAAS app that does this simply and quickly now so you don't have to hardcode and can save time: Json Data
Upvotes: 0
Reputation: 468
One possible solution would be to poll the server for JSON using an XMLHttpRequest. Your client-side JavaScript would look like:
setInterval(updateList, 5000); // run updateList() every 5 seconds
// This assumes you're using jQuery
// You can still do this without jQuery, it just makes things easier
function updateList()
{
$.getJSON('<<URL to your JSON producing script here>>', function(data) {
var items = [];
$.each(data, function(fruit, time) {
items.push('<li>' + time + ' seconds ago: ' + fruit + '</li>');
});
$('#my-list').html(items.join(''));
});
}
And your HTML might look like this:
<ul id='my-list'>
</ul>
Finally, your JSON should follow this format:
{
'Pinapple' : 2,
'Apple' : 22,
'Banana' : 42,
'Grape' : 52,
}
Upvotes: 1