2014-11-17 3 views
1

google 개발자 페이지에서 제공되는 "키워드로 검색"에 대한 javascript 예제가 저에게 효과적이지 않습니다. https://developers.google.com/youtube/v3/code_samples/javascript 코드를 실행하면 "cats"가 포함 된 검색 창이 비활성화됩니다. 또한이 예는 클라이언트 ID가 아닌 API 키를 작성하는 방법을 설명하지 않습니다. 그것은 가능하다고 말하지만 그것을하는 방법에 대한 구체적인 예를 제시하지 못합니다. 누군가이 코드가 잘못된 부분을 지적 할 수 있습니까?youtube api v3 키워드로 검색 javacript

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> 
을 다음과 같이 두 가지의 .js 파일과 HTML에 대한 코드는

답변

3

설명서에 약간의 오해가있을 수 있습니다 (잘못된 내용 일 수도 있음). "키워드로 검색"을위한 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> 

, 당신은 또한 "후 인증"의 클래스를 추가 할 수 있습니다 : 당신이 제공 auth.js를 사용하는 경우 Bascially, 당신은, 당신의 HTML에있는이처럼 보이는 부분이 필요합니다 기존 버튼과 검색 컨테이너를 감싸는 새로운 div에서 데모는 사용자가 방문 할 때 로그인 링크 만 표시합니다. 클릭하면 사용자가 승인을 허용하면 로그인 링크가 숨겨지고 검색 영역이 표시되고 버튼이 활성화됩니다. 데모가 설정되는 방법입니다. 물론

는 (그래서 당신의 버튼을 gapi.client.load() 전화)) 결코 불가능하고, B는 제거) A와 더 쉽게 handleApiLoaded 방법을 찾을 수 있습니다, 키워드로 검색 OAuth2를 필요로하지 않으며, 그래서 (당신의 두번째 질문에 대답) 수동으로 (즉, oAuth 성공에 의해 트리거되지 않음). 그런 다음 모든 요청에 ​​자신의 헤더에 키가 포함되도록 gapi.client.setApiKey({YOUR KEY})으로 전화하십시오.

1

감사합니다. jlmcdonald님께 도움을 청합니다. 답변의 두 번째 부분을 파악하는 데는 시간이 걸렸지 만 마침내 성공했습니다. 다음 html은 Google 개발자 웹 페이지에서 예제를 얻습니다. 처음에는 401 오류가 발생했습니다. 이 문제를 해결하기 위해 Google 개발자 콘솔로 이동하여 내 프로젝트를 선택해야했습니다. 그런 다음, API를 & 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> 

, 당신은 내가 그들을 클릭하면 그때 축소판과 결과의 제목 등을 표시 할 수있는 방법을 설명 할 수 비디오가 열립니다 동일한 페이지에 내장 플레이어가 있습니까? 감사.

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

+0

이 코드는 질문에 대한 답 방법에 대해 자세히 설명하십시오. – JAL