【发布时间】:2017-01-03 16:24:11
【问题描述】:
在尝试使用 JS 与 Youtube API 交互时,我似乎遇到了这个错误。这是我收到的控制台错误。
Uncaught TypeError: Cannot read property 'search' of undefined
at HTMLFormElement.<anonymous> (app.js:7)
at HTMLFormElement.dispatch (jquery-2.2.4.min.js:3)
at HTMLFormElement.r.handle (jquery-2.2.4.min.js:3)
这是我用来交互的脚本。
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 api 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("myapikey");
gapi.client.load("youtube", "v3", function() {
/* check if api is ready */
});
}
最初帮助我编写脚本的人告诉我,除非它在实际的网络服务器(如 Apache)上,否则它有问题,但我是这样,所以我不明白是什么导致了问题。有什么想法吗?
【问题讨论】:
-
嗨,你从哪里引用
gapi? YouTube 对象似乎是未定义的。 API 访问密钥是否具有正确的凭据?这需要在 Google 控制台上创建新应用程序时进行设置。 -
它在我的 HTML 的底部,对此感到抱歉。它肯定也是在 Google 控制台中设置的,这让我很困惑。
-
问题可能与
client.load异步有关,并且当 API 未准备好时调用search。 stackoverflow.com/questions/24586072/…。它看起来也不像init被调用过。如果您在页面加载时调用它应该没问题,因为在表单提交之前搜索不会运行。 -
你能举个例子吗?抱歉,除了我的任务之外,JS 真的一点都不好。
-
您也可以发布 HTML 吗?
标签: javascript youtube