Reputation: 3875
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?
Upvotes: 1
Views: 2099
Reputation: 78971
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>');
});
});
Upvotes: 3
Reputation: 1727
Hm, if you put the JSON in an array, like so (which works for multiple items)
[
{'name':'maverick', 'image':'Jason'},
{'name':'Darlig', 'image':'Rose'}
]
(note wrapping everything in [
and ]
which signifies JSON array)
Now you can just use a for loop
for (var i = 0; i < response.length; i++) {
var currentPerson = response[i];
var currentName = currentPerson.name;
var currentImage = currentPerson.image;
//use currentName and currentImage to add to the DOM
}
Upvotes: 0
Reputation: 5662
Loop through the JSON and append a div:
$.each(data, function(i, item) {
$('#main').append('<div class="a"> name: ' + item.name + ' <img src="img/' + item.image + '.jpg" /></div>');
);
Upvotes: 1