raklos
raklos

Reputation: 28545

jquery iterate json object

Hi I have a json array being returned from the server.. it looks something like this:

[{ ImageUrl="http://www.google.com"}, { ImageUrl="http://www.bing.com"}]

I have this:

<div id="images"></div>

and Im trying to create images based on the data, but I'm struggling with the jquery

$.each(json.imageData.ImageUrl, function (i, ImageUrl) {
  $("<img/>").attr("src", ImageUrl).appendTo("#images");

});

How can i make it add images to the div?

Upvotes: 0

Views: 4240

Answers (1)

mekwall
mekwall

Reputation: 28974

Firstly, your JSON is invalid. You can validate it here: http://jsonlint.com

I think what you are trying to do, is this:

[
    {
        "ImageUrl": "http://domain.com/image.jpg"
    },
    {
        "ImageUrl": "http://domain.com/image2.jpg"
    }
]

Notice the double quotes that were missing in your code. In JSON you are required to use double quotes (never single or without quotes) on both the key and value.

Secondly, you are trying to iterate the value and not the array.

Try with this:

$.each(json.imageData, function (i, img) {
    $("<img>").attr("src", img.ImageUrl).appendTo("#images");
});

Upvotes: 4

Related Questions