1

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?

3 Answers 3

3

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>');
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

@Ted, If you loading json from another domain then you will be restricted by cross domain policy, on that you have to use jsonp request.
1

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>');
); 

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.