【问题标题】:Youtube API only loads on first page visitYoutube API 仅在第一页访问时加载
【发布时间】:2014-02-23 09:35:48
【问题描述】:

我编写了一个小型移动网络应用程序来通过手机在我的 PC 上控制 YouTube,但是在使用 YouTube API 进行搜索时发生了一些奇怪的事情。第一次加载页面时,一切正常 - 输入搜索词,单击搜索并返回结果。

但是,如果我点击另一个页面然后返回,搜索将不再有效,并且我在下面的搜索功能中看到“Uncaught TypeError: Cannot read property of '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 也在使用中,所以我不知道那里是否有什么有趣的事情,但在这一点上的任何想法都会非常感谢!

【问题讨论】:

    标签: javascript jquery api youtube


    【解决方案1】:

    确保在onYouTubeApiLoad() 执行后调用search()。 如果您将search() 绑定到点击事件,请确保在回调中这样做:

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

    【讨论】:

    • 感谢您的建议,我已经尝试过了,但不幸的是仍然遇到同样的问题。在这一行的搜索函数本身内部抛出错误: var request = gapi.client.youtube.search.list({....
    【解决方案2】:

    看来我想通了。看起来 API 的初始加载是在它第一次加载脚本时完成的

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

    但在离开和返回页面时没有再次加载。我添加了 onClientLoad();到

    $( document ).ready 函数现在似乎可以工作了。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2011-03-30
    • 2016-03-12
    • 1970-01-01
    相关资源
    最近更新 更多