2014-01-30 62 views
1

我已經編寫了一個小型移動Web應用程序,以通過手機在我的PC上控制YouTube,但使用YouTube API進行搜索時發生了一些奇怪的事情。第一次加載頁面時,一切都很好 - 輸入搜索詞,單擊搜索並返回結果。Youtube API僅在第一頁訪問時加載

但是,如果我點擊另一個頁面然後回來,搜索不再起作用,並且我在下面的搜索功能中看到「Uncaught TypeError:無法讀取'search'undefined」的屬性。

我對JavaScript很陌生,所以請隨時反饋代碼,但我已經看到這個問題一段時間了,儘管大量的谷歌搜索一直沒能找到解決方案。

// Called automatically when JavaScript client library is loaded. 

function onClientLoad() 
{ 

// 
try 
{ 
gapi.client.load('youtube', 'v3', onYouTubeApiLoad); 
} 

// Called automatically when YouTube API interface is loaded. 
function onYouTubeApiLoad() 
{ 
gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); 
} 

function search(q) { 
// Create api request and execute it 

var request = gapi.client.youtube.search.list({ 
type: 'video', 
     part: 'snippet', 
     q: q 
}); 
     // Send the request to the API server, 
     // and invoke onSearchRepsonse() with the response. 
     request.execute(onSearchResponse); 
} 

function onSearchResponse(response) { 
showResponse(response); 
} 

鏈接到API的腳本是我search.aspx頁面如下圖所示:也被用於

<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script> 

JQuery的,所以我不知道是否有變形產生的任何不道德的行爲但在這一點上,任何想法都將非常感謝!

回答

0

貌似我想通了。它看起來像當它第一次加載腳本

<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script> 

但離開和回來的頁面時則不會重新加載該API的初始加載完成。我加了onClientLoad();到

$(document).ready函數似乎現在正在工作。

+0

如果client.js是服務器上的本地文件(/ lib/client.js),那麼看起來回調參數將被忽略:http://stackoverflow.com/a/37303942/988591。 –

1

確定您在onYouTubeApiLoad()執行後致電search()。 如果綁定search()的單擊事件,確保在回調這麼做:

function onYouTubeApiLoad() 
{ 
    gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); 
    $("button#search").on("click", function(){ search(...); }) 
} 
+0

感謝您的建議,我試過這個,但不幸的是仍然得到同樣的問題。錯誤發生在搜索功能本身的內部: var request = gapi.client.youtube.search.list({.... –