我有以下代码,试图用YouTube Data API
进行搜索。我正在使用express generated stack
和jade
。
#player
script.
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '345',
width: '540',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
function googleApiClientReady() {
gapi.client.setApiKey('AIzaSyCgOmTzCI4-gkUhL4hOm9R6I9tmUlVqtCw');
gapi.client.load('youtube', 'v3', function() {
/**
* This function searches for videos related to the keyword 'dogs'. The video IDs and titles
* of the search results are logged to Apps Script's log.
*
* Note that this sample limits the results to 25. To return more results, pass
* additional parameters as documented here:
* https://developers.google.com/youtube/v3/docs/search/list
*/
function searchByKeyword() {
var results = YouTube.Search.list('id,snippet', {q: 'dogs', maxResults: 25});
for(var i in results.items) {
var item = results.items[i];
console.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
}
}
searchByKeyword();
});
}
script(src="https://apis.google.com/js/client.js?onload=googleApiClientReady")`
根据我的代码,我认为它应该加载一个视频(它确实加载了),然后搜索"狗",并将结果记录到控制台。
然而,我收到错误:
ReferenceError: YouTube is not defined
我不知道我做错了什么。。。脚本没有加载的东西可能。。。但我想,我已经试着在所有可能的地方加载脚本了。
谢谢。
更新
我再次将script(
放在底部——就像在我的原始代码中一样。。。现在我可以确认searchByKeyword
方法正在运行。。。但是问题又回到了CCD_ 7问题。在下面的块中,第一行来自我在searchByKeyword
方法开头放的console.log消息,第二行是相同的错误(这篇文章的标题):
searchByKeyword is running
ReferenceError: YouTube is not defined
您最初的问题是,当gapi.client
加载时,它扩展了基本gapi
对象。要访问Youtube api,请使用gapi.client.youtube.search
而不是Youtube.Search
。
此外,Javascript本质上是异步的,因此任何XHR请求的返回都必须在回调或promised中。
function searchByKeyword() {
var request = gapi.client.youtube.search.list({
q: 'dogs',
part: 'snippet'
});
request.execute(function(results) {
for(var i in results.items) {
var item = results.items[i];
console.log('[%s] Title: %s', item.id.videoId,item.snippet.title);
}
});
}
}