June 20, 2013
Adding div from JSON in jQuery?
Ted’s Question:
I am getting some data from a page in JSON format
JSON:
{
‘name’ : ‘maverick’,
Image : ‘Jason’
}
I now need to take these values and add them to the #main div.
<div id="main">
<div class="a"> name: Eithan <img src="img/Eithan.jpg" /> <div>
<div class="a"> name: Emma <img src="img/Emma.jpg" /> <div>
</div>
How do I do that in jQuery for the case there are several objects in the JSON?
You can do this by using $.getJSON()
function.
$.getJSON("link/to/json", function(data) {
$.each(data, function(i, item) {
$('#main').append('<div class="a"> name: ' + item.name + ' <img src="img/' + item.image + '.jpg" /></div>');
});
});