user992731
user992731

Reputation: 3520

load images from array in json

Not sure why this is not loading. Any help would be great.

//images.json

{  
 "images": [
  {"title": "Image One", "url": "image1.jpg"},
  {"title": "Image Two", "url": "image2.jpg"},
  {"title": "Image Three", "url": "image3.jpg"}
 ]
}

//application.js

function loadImages(url, container) {
    //get the JSON object
    $.getJSON(url, function (data) {
        if (typeof data === 'object') {
            $.each(data['images'], function (key, image) {
                var mylist = '<li><img src="' + image['url'] + '" alt="' + image['title'] + '"></li>';
                $(body).append(mylist);
            });
        }
    });
};


 $(function(){
     loadImages('images.json', '#mylist');
  });

//html

 <ul id="mylist"></ul>

Upvotes: 0

Views: 3171

Answers (4)

phnkha
phnkha

Reputation: 7872

It should be:

$(container).append(mylist);

Upvotes: 1

Rongsir
Rongsir

Reputation: 91

You need one level more loop:

$.each(data, function (key, image) {
    $.each(image, function(i,val){
        var mylist = '<li><img src="' + val.url + '" alt="' + val.title + '"></li>';
        $('body').append(mylist);
    })
});

Of course, if you wanna append to container, change $('body') to $(container)

Upvotes: 0

ekrembk
ekrembk

Reputation: 410

There's nothing like $(body), it should be $('body'). Also in your case it must be $(container)

Upvotes: 0

Ant&#243;nio Almeida
Ant&#243;nio Almeida

Reputation: 10087

You've missed the quotes here:

$(body).append(mylist); 

It should be:

$('body').append(mylist);

Upvotes: 0

Related Questions