我对新的YouTube API有疑问。通过ajax调用版本2我可以将最后一个视频上传到播放列表,我该如何处理新的API?谢谢你的支持。
编辑
感谢您的回答,我尝试了代码,但返回了一个javascript错误:“无法在html代码下方读取属性'setApiKey'未定义”:
<!doctype html>
<html>
<head>
<title>YouTube</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
<script>
gapi.client.setApiKey('{API-KEY-HERE}');
gapi.client.load('youtube', 'v3', function () {
var request = gapi.client.youtube.playlistItems.list({
part: 'snippet',
playlistId: 'PLTK1i0pncVu_tLhgrPo_o7QcRocqozxUv'
});
request.execute(function (response) {
response.items.sort(function(a,b) {return a.snippet.publishedAt < b.snippet.publishedAt})
for (var i=0; i<response.items.length;i++)
{
console.log(response.items[i].snippet.title + " published at " + response.items[i].snippet.publishedAt)
}
});
});
</script>
</body>
</html>
答案 0 :(得分:0)
这样的内容会加载指定播放列表的所有视频,并按publishedAt
排序。对于最新的视频,只需获得第一个结果。
<!doctype html>
<html>
<head>
<title>YouTube</title>
</head>
<body>
<script>
var allVideos = new Array();
function onGoogleLoad() {
gapi.client.setApiKey('{YOUR-API-KEY}');
gapi.client.load('youtube', 'v3', function() {
GatherVideos("", function() {
allVideos.sort(function(a, b) {
return Date.parse(b.snippet.publishedAt) - Date.parse(a.snippet.publishedAt);
})
for (var i = 0; i < allVideos.length; i++) {
console.log(allVideos[i].snippet.title + " published at " + allVideos[i].snippet.publishedAt)
}
});
});
}
function GatherVideos(pageToken, finished) {
var request = gapi.client.youtube.playlistItems.list({
part: 'snippet',
playlistId: 'PLTK1i0pncVu_tLhgrPo_o7QcRocqozxUv',
maxResults: 50,
pageToken: pageToken
});
request.execute(function(response) {
allVideos = allVideos.concat(response.items);
if (!response.nextPageToken)
finished();
else
GatherVideos(response.nextPageToken, finished);
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=onGoogleLoad"></script>
</body>
</html>