Scott Riley Scott Riley - 3 years ago 91
Javascript Question

Display an image from JSON using jQuery

I have the following jQuery code at the moment.

Note that to run the snippet here you need to click and allow this first:

https://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topTvEpisodes/json



(function() {
var iTunesAPI =
"https://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topTvEpisodes/json";
$.getJSON(iTunesAPI)
.done(function(data, textStatus) {
$.each(data.feed.entry, function(i, ent) {
$("<li>" + ent.title.label + "</li>").appendTo("#tvshow");
});
console.log("Yippee " + textStatus);
})
.fail(function(jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err + " " + jqxhr.status);
})
.always(function() {
console.log("Whatever");
})
})();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<ul id="tvshow">
<ul>





This displays a list of TV shows with the titles of the TV shows which are numbered into a list. I am currently trying to find a way to extract the image from the JSON using jQuery but I am unable to do so. I thought I could just add

+ ent.title.image


Into the line with the
<li>
tags but this then just returns a list saying "undefined".

Any help pointing me in the right direction of how I can extract images would be grateful, I am new to jQuery so learning as I go along.

Thanks,
Scott

Answer Source

you should call image from JSON like

ent["im:image"][0].label

for example:

$("<li><img src='"+ ent["im:image"][0].label +"'/>" + ent.title.label + "</li>").appendTo("#tvshow");

Note: I have change the service call from http to https to demo over https fiddle

(function() {
  var iTunesAPI = 
  "//ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topTvEpisodes/json";
  $.getJSON( iTunesAPI )
    .done(function( data, textStatus ) {
      $.each( data.feed.entry, function( i, ent ) {
        $("<li><img src='"+ ent["im:image"][0].label +"'/>" + ent.title.label + "</li>").appendTo("#tvshow");
      });
      console.log( "Yippee " + textStatus );
    })
    .fail(function( jqxhr, textStatus, error ) {
        var err = textStatus + ", " + error;
        console.log( "Request Failed: " + err + " " + jqxhr.status );
    })
    .always(function() {
        console.log( "Whatever" );
    })
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="tvshow">
</ul>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download