谷歌开发者页面上给出的"按关键字搜索"的javascript示例对我不起作用。 https://developers.google.com/youtube/v3/code_samples/javascript当我运行代码时,我得到一个禁用的搜索框,里面有"猫"。 此外,该示例未说明如何写入 API 密钥而不是客户端 ID。 它说这是可能的,但没有给出如何做到这一点的具体例子。 有人可以指出这段代码出错的地方吗? 两个.js文件和 html 的代码如下所示:
身份验证.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();
});
}
搜索.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>');
});
}
搜索.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>
文档有点误导(甚至可以说不正确); "按关键字搜索"的 HTML 正在加载与该页面上的其他两个示例相同的"身份验证.js",但它没有任何 HTML 元素来实际触发登录过程(即,如果用户尚未获得授权,则使用"登录按钮"),就像其他两个示例一样。 基本上, 如果您使用的是提供的身份验证.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>
然后,您还可以在围绕现有按钮和搜索容器的新div 上添加"后身份验证"类。然后,当用户访问时,演示将仅显示登录链接;单击后,当用户允许授权时,登录链接将被隐藏,您的搜索区域将显示(并启用按钮)。这就是演示的设置方式。
当然,按关键字搜索不需要 oAuth2,因此(要回答您的第二个问题)您可能会发现 A) 删除 handleApiLoaded
方法(因此您的按钮永远不会被禁用)和 B) 手动调用gapi.client.load()
(即不是由 oAuth 成功触发)。然后,调用 gapi.client.setApiKey({YOUR KEY})
,以便所有请求的标头中都包含您的密钥。
非常感谢jlmcdonald的帮助。 我花了一段时间才弄清楚你回应的第二部分,但我终于成功了。 以下 html 使 google 开发者网页上的示例正常工作。 请注意,起初我收到 401 错误。 为了修复它,我必须去谷歌开发者控制台并选择我的项目。 然后,APIs>同意屏幕,然后填写电子邮件地址和产品名称:
<!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上的帖子是未定义的?真的帮我弄清楚了:
<!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>
现在我得到了搜索部分,您能否解释一下如何显示结果的缩略图和标题,然后当我单击它们时,视频在同一页面上的嵌入式播放器中打开? 谢谢。
感谢您的编码。让我分享我的代码:
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>
}