Hi im trying to populate ul in html with JSON, i have tried many solutions from this site, but im not having much luck, any suggestions would be gratefully appreciated. Thanks
my code :
<script>
$.getJSON('/simplepie/round/alltables.json', function (data) {
var o = null;
var myArray = new Array();
document.open();
for( var i = 0; i < data.length; i++ )
{
o = data[i];
myArray.push('<li>' + o.title + '</li>');
//document.write(o.source + " <br>" + o.description + "<br>") ;
myArray.push(o.source);
makeUL(o.source);
}
//document.close();
// document.write('Latitude: ' + data.id + '\nLongitude: ' + data.title + '\nCountry: ' + data.description);
function makeUL(array) {
var list = document.createElement('ul');
for(var i = 0; i < array.length; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
});
</script>
</head>
<body>
<ul id="ct"></ul>
</body>
JSON structure
[{"id":"1","source":"Articles | Mail Online",
"time_date":"1422720360",
"title":"Rouhani accuses Iranian hardliners of ",
"description":"DUBAI, Jan 31 (Reuters) - Iranian President Hassan Rouhani",
"link":"http:\/\/www.dailymail.co.uk\/wires\/reuters\/article-2934402\/Rouhani-accuses-Iranian-hardliners-cheering-atom-talks.html?ITO=1490&ns_mchannel=rss&ns_campaign=1490",
"image":"http:\/\/i.dailymail.co.uk\/i\/pix\/m_logo_154x115px.png"}]
Replace your loop with this:
Get a handle on your List since its already in your body <ul id="ct"></ul>
:
var ul = document.getElementById("ct");
Then create the li using javascript and append it to your list:
for( var i = 0; i < data.length; i++ )
{
var obj = data[i];
var li = document.createElement("li");
li.appendChild(document.createTextNode(obj.title));
ul.appendChild(li);
}
There is no need for your MakeUL function
Here is a JS Fiddle to help you: http://jsfiddle.net/loanburger/6nrx1zkj/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With