Youtube API,gapi 没有定义? [英] Youtube API, gapi is not defined?

查看:23
本文介绍了Youtube API,gapi 没有定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个 Youtube API,我觉得除了这个 gapi 和 res 之外,我的一切都在工作?它说gapi没有定义.我怎样才能使这项工作?

I'm trying to do a Youtube API and I feel like I got everything working except this gapi and res thing? It says gapi is not defined. How can I make this work?

function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}

$(function() {
    $("form").on("submit", function(e) {
       e.preventDefault();
       // prepare the request
       var request = gapi.client.youtube.search.list({
            part: "snippet",
            type: "video",
            q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
            maxResults: 3,
            order: "viewCount",
            publishedAfter: "2015-01-01T00:00:00Z"
       }); 
       // execute the request
       request.execute(function(response) {
          var results = response.result;
          $("#results").html("");
          $.each(results.items, function(index, item) {
            $.get("tpl/item.html", function(data) {
                $("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}]));
            });
          });
          resetVideoHeight();
       });
    });

    $(window).on("resize", resetVideoHeight);
});

function resetVideoHeight() {
    $(".video").css("height", $("#results").width() * 9/16);
}

function init() {
    gapi.client.setApiKey("AIzaSyD646m4ZfK5yKBZj9p95LohN-PTUnRHBRY");
    gapi.client.load("youtube", "v3", function() {
    });
}

推荐答案

gapi 是一个由 Google API javascript 库创建的对象,用于管理所有交互(即完成所有繁重的请求)为你.如果未定义对象,则您可能没有在页面中包含库本身.在 HTML 中的某处,您需要一个脚本标记来加载位于以下位置的库:

gapi is an object created by the Google API javascript library that manages all interactions (i.e. does all the heavy lifting of the requests) for you. If the object is not defined, you may not have included the library itself in your page. Somewhere in your HTML, you'll need a script tag that loads the library located at:

https://apis.google.com/js/client.js

请注意,在使用脚本标记加载库时,您还应该向它传递一个回调......这是一个函数,一旦库加载完成,它就会自动调用.所以在你的情况下,你的 init() 方法就是那个回调,所以你的脚本标签看起来像这样:

Note that, in loading the library with a script tag, you should also pass it a callback ... this is a function that will be automatically called as soon as the library is done loading. So in your case, your init() method is that callback, and so your script tag would look like this:

<script src="https://apis.google.com/js/client.js?onload=init"></script>

浏览器将获取库,加载它,然后在库加载完成后运行 init(),所有这些都准备好让您的表单在触发时执行.

The browser will get the library, load it, then run init() when the library is done loading, and all will be ready for your form to execute when triggered.

这篇关于Youtube API,gapi 没有定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆