我对新的YouTube API有一个问题。与版本2通过ajax调用我可以采取最后一个视频上传到播放列表,我该如何与新的API ?谢谢您的支持。
编辑
感谢您的回答,我尝试了代码,但返回一个javascript错误:"不能读取属性'setApiKey'的未定义"下面的html代码:
<!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>
类似这样的东西将加载指定播放列表的所有视频并按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>