【问题标题】:youtube api v3 search by keyword javascriptyoutube api v3 按关键字搜索 javascript
【发布时间】:2015-01-14 12:32:49
【问题描述】:

谷歌开发者页面上给出的“按关键字搜索”的 javascript 示例对我不起作用。 https://developers.google.com/youtube/v3/code_samples/javascript 当我运行代码时,我得到一个禁用的搜索框,里面有“猫”。此外,该示例没有说明如何写入 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>');
 });
}

搜索.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>

【问题讨论】:

    标签: javascript youtube youtube-api youtube-data-api


    【解决方案1】:

    文档有点误导(甚至可能会说不正确); “按关键字搜索”的 HTML 正在加载与该页面上的其他两个示例相同的“auth.js”,但它没有任何 HTML 元素来实际触发登录过程(即“登录按钮" 如果用户尚未获得授权),就像其他两个示例一样。基本上,如果您使用的是提供的 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>
    

    然后,您还可以在围绕现有按钮和搜索容器的新 div 上添加“post-auth”类。然后,该演示将在用户访问时仅显示登录链接;当点击时,当用户允许授权时,登录链接将被隐藏,您的搜索区域将显示(并启用按钮)。这就是演示的设置方式。

    当然,按关键字搜索不需要 oAuth2,因此(回答您的第二个问题)您可能会发现 A)删除 handleApiLoaded 方法(因此您的按钮永远不会被禁用)和 B)调用更容易gapi.client.load() 手动(即不是由 oAuth 成功触发)。然后,调用gapi.client.setApiKey({YOUR KEY}),这样您的所有请求都将在其标头中包含您的密钥。

    【讨论】:

      【解决方案2】:

      非常感谢 jlmcdonald 的帮助。我花了一段时间才弄清楚你回复的第二部分,但我终于成功了。以下 html 使 google 开发人员网页上的示例正常工作。不过请注意,起初我收到 401 错误。要修复它,我必须去谷歌开发者控制台并选择我的项目。然后,APIs&auth->同意屏幕,然后填写邮箱地址和产品名称:

      <!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>
      

      现在我得到了搜索部分,您能否解释一下如何显示结果的缩略图和标题,然后当我点击它们时,视频会在同一页面上的嵌入式播放器中打开?谢谢。

      【讨论】:

        【解决方案3】:

        感谢您的编码。让我分享我的代码:

        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>
          }

        【讨论】:

        • 请详细说明这段代码是如何回答这个问题的。
        猜你喜欢
        • 1970-01-01
        • 2016-07-13
        • 1970-01-01
        • 2013-12-03
        • 1970-01-01
        • 2013-09-03
        • 2014-10-22
        • 2020-09-03
        • 1970-01-01
        相关资源
        最近更新 更多