j bel
j bel

Reputation: 153

loading images from json file with jquery

So I have a json file which now loads text and images individually pretty fine, this is just a simple example of what I did to test if it would work:

  outputc+="<li>"
  outputc+=this.name+" "+this.price+"</li>";
  $('#featured').append(outputc);
  $("<img/>").attr('src',this.images).appendTo('#featured');

Using the above code works perfectly however i need for both of these to be wrapped with a list, so I did some searching and I found this:

$(document).ready(function(){

//loading json file

var url = "shoppingItems.json";

$.getJSON(url,function(json){


    $.each(json.shoppingItem,function()
    {
        var output ='<li><img src= "'+this.images+'" alt ="'+this.name+'"></li>';
    });

    $('.items').append(output);
});
});

The above jQuery doesn't bring back anything at all, there isn't anything wrong with my json file as it's been validated and the code works if I simply alert it. This is potentially something I must be doing wrong with my output script which I can't see.

My JSON file can be found here: Json file not loading or showing alerts

Upvotes: 3

Views: 5414

Answers (1)

Blazemonger
Blazemonger

Reputation: 92983

Since you declare it inside the callback function as var output, the output variable is local to that callback function and vanishes once the loop is completed. Even if that wasn't the case, the use of the = operator would mean you were overwriting the previous value with each iteraction.

Try this:

var output = ""; // initialize it outside the loop
$.each(json.shoppingItem,function()
{
    output += '<li><img src= "'+this.images+'" alt ="'+this.name+'"></li>';
});
$('.items').append(output);

http://jsfiddle.net/mblase75/zB5fv/

Upvotes: 7

Related Questions