youtube api v3 търсене по ключова дума javascript

Примерът на javascript за „търсене по ключова дума“, който е даден на страницата за разработчици на Google, не работи за мен. https://developers.google.com/youtube/v3/code_samples/javascript Когато стартирам кода, получавам деактивирано поле за търсене с „котки“ вътре. Освен това примерът не обяснява как да пишете в API ключа за разлика от ИД на клиента. Казва, че е възможно, но не дава конкретен пример как да го направим. Може ли някой да посочи къде греши този код. Кодът за двата .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>

person user3080392    schedule 17.11.2014    source източник


Отговори (3)


Документацията е малко подвеждаща (дори може да се каже невярна); 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="/bg#" id="login-link">authorize</a> to continue.
</div>

След това можете също да добавите класа "post-auth" към нов div, който обвива вашите съществуващи бутони и контейнер за търсене. След това, когато потребител посети, демонстрацията ще представи само връзката за влизане; когато се щракне върху него и когато потребител разреши оторизацията, тогава връзката за влизане ще бъде скрита и вашата зона за търсене ще бъде показана (и бутонът е активиран). Просто така е настроена демонстрацията.

Разбира се, търсенето по ключова дума НЕ изисква oAuth2 и така (за да отговорите на втория си въпрос) може да ви е по-лесно да A) премахнете метода handleApiLoaded (така че бутонът ви никога да не е деактивиран) и B) да извикате gapi.client.load() ръчно (т.е. не задействано от успех на oAuth). След това се обадете на gapi.client.setApiKey({YOUR KEY}), така че всички ваши заявки да включват вашия ключ в заглавката си.

person jlmcdonald    schedule 19.11.2014

Благодаря много, jlmcdonald за вашата помощ. Отне ми известно време да разбера втората част от отговора ви, но най-накрая постигнах успех. Следният html кара примера на уеб страницата на разработчиците на Google да работи. Обърнете внимание обаче, че първоначално получавах грешка 401. За да го поправя, трябваше да отида в конзолата за разработчици на Google и да избера своя проект. След това екран APIs&auth->consent и след това попълнете имейл адреса и името на продукта:

<!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="/bg#" 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 не е необходим за обикновено търсене по ключови думи. Следва малко html, който просто използва API ключа. Не споменах двата .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>

Сега, след като получих частта за търсене, бихте ли обяснили как мога да покажа миниатюрите и заглавията на резултатите и след това, когато щракна върху тях, видеоклипът се отваря във вграден плейър на същата страница? Благодаря.

person user3080392    schedule 19.11.2014

Благодаря ви за кодирането. Нека споделя моя код:

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="/bg#" 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>
  }

person hung phan    schedule 24.02.2016
comment
Моля, разяснете как този код отговаря на въпроса. - person JAL; 24.02.2016