尝试使用 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)上,否则它有问题,但我的是,所以我不明白是什么导致了问题。有任何想法吗?
最佳答案
您的问题似乎是缺少对 init
的任何调用。方法。添加行 init();
以上$("form").on("submit", function(e) { ...
我已经尝试过了,并收到了一个未经授权的异常,正如您对 dud API key 所期望的那样。
关于javascript - 无法读取未定义的属性 'search' - Youtube API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41447890/