aurel
aurel

Reputation: 3132

How to loop through all json items with jquery?

This is the json file I am working with

?(
{
    "title":"1",
    "description":"description",
    "site":"site",
    "image_s":"/Becki.jpg",
    "image_l":"aurel"
},
{
    "title":"2",
    "description":"2",
    "site":"1",
    "image_s":"8.jpg",
    "image_l":"aurel"
})

The question mark is replaced with a dynamic number in order to over come cross-domain restrictions. And I think this is why I am having trouble

I am trying to get both image_s but I can only read the data of the first item (if that's the right word):

$.getJSON(surl,  function(data) {
        $.each(data, function(tete, i){
            $.each(data, function(tete, i){
                    $("<div>").addClass("box").append(
                        $("<img/>").attr("src", [this]))
                        ).appendTo("#showdata");
            });

        })
   }); 

I know there is something wrong with $("<img/>").attr("src", [this])) but that is not the problem. The problem is that the above loop only get the content of the first item (title:1 to the end not title:2)

I think if the name of the question mark wasn't dynamic I could have done the loop from there and got its children, but I dont know how to do that in this case

And in case you need to know, I can not use server-side programing for this particular project

Can you help in any way?

Upvotes: 1

Views: 1484

Answers (2)

rkw
rkw

Reputation: 7297

If you're passing data through another domain, you're probably using JSONP. JSONP requires the server to return the values wrapped in a function; in your case, the function is a random string of numbers.

If your post is accurate, you'll have to update the server to return the JSON object properly:

Currently it is returning multiple objects wrapped by a function: 235235({one object}, {two object})

When it should be returning one JSON object, wrapped by a function: 235235([{first object in array}, {second object in array}])

Upvotes: 0

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28015

You have to put your items (called objects in JavaScript) into array:

[
    {
        "title":"1",
        "description":"description",
        "site":"site",
        "image_s":"/Becki.jpg",
        "image_l":"aurel"
    },
    {
        "title":"2",
        "description":"2",
        "site":"1",
        "image_s":"8.jpg",
        "image_l":"aurel"
    }
]

And also change your JS:

$.each(data, function(index, item){
       $("<div>").addClass("box")
           .append($("<img/>").attr("src", [item.image_s]))
           .appendTo("#showdata");
});

Running example is shown in this JSFiddle.

Upvotes: 2

Related Questions