"按关键字"搜索的javascript示例在谷歌开发者页面上给出的并不适合我。 https://developers.google.com/youtube/v3/code_samples/javascript 当我运行代码时,我会使用" cats"内。此外,该示例没有解释如何写入API密钥而不是客户端ID。它说这是可能的,但没有提供如何做的具体例子。有人可以指出这段代码出错的地方。两个.js文件和html的代码如下:
auth.js文件:
// The client ID is obtained from the Google Developers Console
// at https://console.developers.google.com/.
// If you run this code from a server other than http://localhost,
// you need to register your own client ID.
var OAUTH2_CLIENT_ID = '__YOUR_CLIENT_ID__';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
// Upon loading, the Google APIs JS client automatically invokes this callback.
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
// Attempt the immediate OAuth 2.0 client flow as soon as the page loads.
// If the currently logged-in Google Account has previously authorized
// the client specified as the OAUTH2_CLIENT_ID, then the authorization
// succeeds with no user intervention. Otherwise, it fails and the
// user interface that prompts for authorization needs to display.
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
} else {
// Make the #login-link clickable. Attempt a non-immediate OAuth 2.0
// client flow. The current function is called when that flow completes.
$('#login-link').click(function() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
});
}
}
// Load the client interfaces for the YouTube Analytics and Data APIs, which
// are required to use the Google APIs JS client. More info is available at
// http://code.google.com/p/google-api-javascript-client /wiki/GettingStarted#Loading_the_Client
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
handleAPILoaded();
});
}
search.js文件:
// After the API loads, call a function to enable the search box.
function handleAPILoaded() {
$('#search-button').attr('disabled', false);
}
// Search for a specified string.
function search() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}
search.html
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="buttons">
<label> <input id="query" value='cats' type="text"/><button id="search-button" disabled onclick="search()">Search</button></label>
</div>
<div id="search-container">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="auth.js"></script>
<script src="search.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>
答案 0 :(得分:3)
文档有点误导(甚至可能说不正确); &#34;按关键字&#34;搜索的HTML加载相同的&#34; auth.js&#34;该页面上的其他两个示例是,但它没有任何HTML元素实际触发登录过程(即#34;登录按钮&#34;如果用户尚未获得授权)像其他两个例子那样。基本上,如果你使用提供的auth.js,你需要在你的HTML中有一个看起来像这样的部分:
<div id="login-container" class="pre-auth">
This application requires access to your YouTube account.
Please <a href="#" id="login-link">authorize</a> to continue.
</div>
然后,您还可以添加&#34; post-auth&#34;在包含现有按钮和搜索容器的新div上。然后,当用户访问时,演示将仅显示登录链接;单击时,当用户允许授权时,将隐藏登录链接,并显示您的搜索区域(并启用按钮)。这就是演示的设置方式。
当然,按关键字搜索不需要oAuth2,所以(为了回答你的第二个问题)你可能会发现更容易A)删除handleApiLoaded
方法(所以你的按钮永远不会被禁用)和B )手动调用gapi.client.load()
(即不是由oAuth成功触发)。然后,请致电gapi.client.setApiKey({YOUR KEY})
,以便您的所有请求都会将您的密钥包含在其标题中。
答案 1 :(得分:1)
非常感谢jlmcdonald的帮助。我花了一段时间来弄清楚你的回答的第二部分,但我终于取得了成功。以下html获取了谷歌开发者网页上的示例。请注意,起初我得到401错误。要修复它,我不得不去谷歌开发者控制台并选择我的项目。然后,API&amp; auth-&gt;同意屏幕,然后填写电子邮件地址和产品名称:
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="login-container" class="pre-auth">
This application requires access to your YouTube account.
Please <a href="#" id="login-link">authorize</a> to continue.
</div>
<div id="buttons" class="post-auth">
<label> <input id="query" value='cats' type="text"/><button id="search-button" disabled onclick="search()">Search</button></label>
</div>
<div id="search-container">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="/files/theme/auth.js"></script>
<script src="/files/theme/search.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>
正如您在回复中所述,oAuth2对于简单的关键字搜索不是必需的。以下是一些只使用API密钥的html。我没有像以前那样引用两个.js文件,相反,我只是将脚本包含在html中。您在gapi.client.youtube is undefined?的帖子确实帮助我解决了问题:
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="buttons">
<label> <input id="query" value='cats' type="text"/><button id="search-button" onclick="keyWordsearch()">Search</button></label>
</div>
<div id="search-container">
</div>
<script>
function keyWordsearch(){
gapi.client.setApiKey('API key here');
gapi.client.load('youtube', 'v3', function() {
makeRequest();
});
}
function makeRequest() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}
</script>
<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=googleApiClientReady"> </script>
</body>
</html>
现在我有了搜索部分,你能解释一下我如何显示结果的缩略图和标题,然后当我点击它们时,视频会在同一页面上的嵌入式播放器中打开吗?感谢。
答案 2 :(得分:0)
感谢您的编码。让我分享一下我的代码:
function makeRequest(){
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response){
var str = JSON.stringify(response.result,'',4);
$('#search-container').val( str);
makeControl(response);
});
}
function makeControl(resp){
var stList = '<table id="res1" border="1" cellspacing="1" width="100%"><tbody>';
for (var i=0; i<resp.items.length;i++){
var vid = resp.items[i].id.videoId;
var tit = resp.items[i].snippet.title;
if(typeof vid != 'undefined'){
stList += '<tr><td style="width:80px;vertical-align:top">'+
'<a class="show" href="#" title="'+ vid + '" onclick="playVid(this);'+
' return false">'+
'<img width="80" height="60" src="http://img.youtube.com/vi/'+
vid +'/default.jpg"></a></td>'+
'<td><b>'+i+'</b>-'+ tit +'</td></tr>';
}
}
document.getElementById('list1').innerHTML = stList + '</tbody></table>';
//HTML: <div id="list1"
//style="width:853px;height:400px;overflow:auto;background-color:#EEEEEE">
//</div>
}
function playVid(thi){
var st = 'https://www.youtube.com/embed/'+thi.title+'?autoplay=1';
document.getElementById('player').src = st;
//HTML: <iframe id="player" width="853" height="480" src="" frameborder="1" allowfullscreen>
//</iframe>
}