播放列表项目返回“未定义”? JQuery / YouTube API v3

时间:2018-02-05 18:41:11

标签: jquery youtube youtube-api youtube-data-api

我试图弄清楚这个问题的根源。我有一个功能可以抓取添加到youtube播放列表中的最新视频,但我似乎无法将该播放列表中的视频链接到指向相应的视频网址。很难过。我做错了什么?

UPDATE /溶液

我已使用提供的解决方案here更新了代码段。将videoID = item['id']['videoId'];替换为videoID = item['snippet']['resourceId']['videoId'];

var htmlString = "";
var apiKey = 'AIzaSyDI4rWo_wVAxRZEIgF6_8sRZDj8OCOZZ38';
var playlistID = 'PLBhKKjnUR0XBVrHvtDOylN5XREHh9X1nt';
var maxResults = 10;

$.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?key=' + apiKey + '&playlistId=' + playlistID + '&part=snippet&maxResults=' + (maxResults > 50 ? 50 : maxResults), function(data) {
  $.each(data.items, function(i, item) {
    var videoID = item['snippet']['resourceId']['videoId'];
    var title = item['snippet']['title'];
    var videoURL = 'https://www.youtube.com/watch?v=' + videoID + '&list=' + playlistID + '&index=1';
    htmlString += '<div class="video">' + title + '<br><a target="_blank" href="' + videoURL + '"><img src="https://i.ytimg.com/vi/' + videoID + '/default.jpg"></a></div>';
  });
  $('#youtube-playlist-feed').html(htmlString);
});
body {
  margin: 0;
  padding: 0;
}

.video {
  float: left;
  max-width: 30%;
  margin: 5px;
  font-size: 20px;
  font-weight: bold;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.video img {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="youtube-playlist-feed"></div>

1 个答案:

答案 0 :(得分:0)

你设置了错误的videoId。

应该是:

var videoID = item['snippet']['resourceId']['videoId'];