使用jQuery从JSON显示图像

时间:2017-09-30 10:27:18

标签: javascript jquery json image

目前我有以下jQuery代码。

请注意,要在此处运行代码段,您需要先点击并允许此内容:

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>

显示电视节目列表,其中包含电视节目的标题,这些节目编号为列表。我目前正在尝试使用jQuery找到从JSON中提取图像的方法,但我无法这样做。我以为我可以添加

+ ent.title.image

进入带有<li>标签的行,但这只返回一个说“未定义”的列表。

任何指导我正确指导我如何提取图像的帮助都会感激不尽,我是jQuery的新手,所以我一边学习。

谢谢, 斯科特

2 个答案:

答案 0 :(得分:3)

具有图像的属性为im:image。所以,你需要以下内容:

$.each( data.feed.entry, function( i, ent ) {
  var imgUrl = ent['im:image'][ ent['im:image'].length - 1 ].label, // the last index returns the highest resolution.
  img = '<img src="' + imgUrl + '"/>';
  $("<li>" + ent.title.label + '<br/>' + img + "</li>").appendTo("#tvshow");
});

答案 1 :(得分:3)

你应该从JSON调用图像,如

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

例如:

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

注意: 我已将服务调用从http改为https,再转换为https小提琴

&#13;
&#13;
(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" );
    })
})();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="tvshow">
</ul>
&#13;
&#13;
&#13;