【发布时间】:2016-01-25 07:12:21
【问题描述】:
我在这里慢慢变得疯狂 :( 我无法获得看似简单的工作。我使用 yt api v3 从频道获取特定播放列表的视频。现在我使用两个 HTTP 请求(频道和播放列表项):
- 获取给定用户名(频道/内容详细信息)的所有上传的播放列表 ID
- 从 html-tag 中的数据属性中获取特定的播放列表 ID
- 使用 id 获取每个播放列表的视频信息 (playlistItems/sn-p)
- 输出视频信息,追加到列表中
到目前为止,此代码有效:
HTML
<h2><span>List 1</h2>
<ul data-plist="PLquImyRfMt6dWNzlyTHW9m353VadxKKg_"></ul>
<h2>List 2</h2>
<ul data-plist="PLquImyRfMt6d4gk6zX8FPEZeyYgE4oBdR"></ul>
<h2>List 3</h2>
<ul data-plist="PLquImyRfMt6fnpIb9VR9c6VLZwYs_OyWL"></ul>
JS/JQUERY:
var channelName = 'goetheinstitut';
var vidResults = 3;
// Get all Videos from the channel via Playlist "uploads"
$.get(
"https://www.googleapis.com/youtube/v3/channels", {
part: 'contentDetails',
forUsername: channelName,
key: 'AIzaSyCu8N1RGBaExofEQtBZHMMpAYNxvirhIBM'
},
function (data) {
$.each(data.items, function (i, item) {
pid = item.contentDetails.relatedPlaylists.uploads;
getVids(pid);
});
});
// Get videos for specific Playlist, id from data attr
function getVids(pid) {
$("[data-plist]").each(function () {
var vidPlaylist = $(this).data('plist');
var mylist = $(this);
// Get and output Playlist Items
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", {
part: 'snippet',
maxResults: vidResults,
playlistId: vidPlaylist,
key: 'AIzaSyCu8N1RGBaExofEQtBZHMMpAYNxvirhIBM'
},
function (data) {
var output;
$.each(data.items, function (i, item) {
videoTitle = item.snippet.title.substring(8);
videoId = item.snippet.resourceId.videoId;
output = '<li><a href=\"//www.youtube.com/embed/' + videoId + '?autoplay=1&showinfo=0&controls=0\"><h3>' + videoTitle + '</h3><small>viewCount</small></a></li>';
//Append to results list
$(mylist).append(output);
});
});
});
}
现在我还需要每个视频的 viewCount。这意味着我必须将每个播放列表的 videoId 存储在一个数组中,然后为 statistics.viewCount 发出新请求 (https://www.googleapis.com/youtube/v3/videos)。但是我无法用我已经拥有的代码来管理它。这是jsfiddle。
这是对 viewCount 的请求,其中包含手动输入的 id 数组:
$.get(
"https://www.googleapis.com/youtube/v3/videos", {
part: 'statistics',
// 3 ids from List 1 - these would have to come as variable
id: '8kFevX-bp8g, L6thExvypGg, D_RBv6Bsm6E',
key: 'AIzaSyCu8N1RGBaExofEQtBZHMMpAYNxvirhIBM'
},
function (data) {
var listviews;
$.each(data.items, function (i, item) {
views = item.statistics.viewCount;
listviews = '<li>'+views+'</li>';
$('#results').append(listviews);
// should be part of the output from the previous function...
});
});
有人可以帮我把这两个请求拼接在一起吗?我总是以一些未定义的变量结束,因为我不在范围内。 :(
【问题讨论】:
标签: javascript jquery youtube-api xmlhttprequest youtube-data-api