I have a JSON object that looks like this.
[
{
"id" : "23",
"event_id" : "0",
"sport_title" : null,
"event_title" : null,
"title" : "Under 1 day!",
"content" : "It\\'s all hotting up and battle commences in under one day!",
"link" : ""
},
{
"id" : "20",
"event_id" : "0",
"sport_title" : null,
"event_title" : null,
"title" : "Getting Exciting",
"content" : "Less than two days till it all kicks off, with cricket....",
"link" : ""
}
]
and I am trying to get the details out of this JSON Object and prepend them to a <ul>
the code that I am currently trying looks like this and is having problems
var writeup_list = writeuplist;
$.getJSON('../json/getWriteups.json', function(data) {
$.each(data.items, function(i, item) {
writeup_list.html(function() {
var output;
output = '<li><a href="/writeups/index.php#writeup_' + item.id + '">';
if(item.sport_title != null) {
output += item.sport_title + ' - ';
}
output += item.title + '</a></li>';
return output;
});
});
});
writeuplist is just the ul object.
I am also worried about overriding information that is already in the list or just adding again. Don’t want to keep adding the same data. What is a good way to avoid this?
I seem to be having a problem in getting the data out of the JSON file I believe it has something to do with the way am trying to access it in the .each function.
Can anyone spot where am going wrong?
Some things to note:
alert(data.items)in the callback, and make sure you see [object Array]).item.sport_titlewill be null? I changed it to check its a string…element.html(str)will replace the current contents. Your sample was replacing the current html with each iteration, so at the end, you’d only have the contents of the last list element in your list.