如何在 javascript w Ajax & JSON 中使用 v3 URL API 获取 Youtube 视频标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28018792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:17:41  来源:igfitidea点击:

How to get Youtube video title with v3 URL API in javascript w Ajax & JSON

javascriptjsonyoutubeyoutube-apiyoutube-javascript-api

提问by Kamy D

I am only trying to fetch Youtube video's title. Can't seem to figure it. So far I have this:

我只是想获取 Youtube 视频的标题。好像想不通 到目前为止,我有这个:

     q = 'https://www.googleapis.com/youtube/v3/videos?id='+ itemId +'&key='+ ytApiKey +'&fields=items(snippet(channelId,title,categoryId))&part=snippet' ;

$.ajax({
      url: q, 
      dataType: "jsonp",
      success: function(data){
               alert(data.items[0].title);
               console.log(data.snippet.title);            
      },
      error: function(jqXHR, textStatus, errorThrown) {
          alert (textStatus, + ' | ' + errorThrown);
      }
  });

Thanks,

谢谢,

回答by Kamy D

I got it working using

我使用它工作

https://www.googleapis.com/youtube/v3/videos?id=itemId&key=apiKey&fields=items(snippet(title))&part=snippet

and

alert(data.items[0].snippet.title);

So, not much wrong with the syntax! But I found that the problem was really in the backend when setting up the Google API's 'allowed referers'. With V3 API, you can select which referers the API should belong to, so others cannot simply steal your API and use it. So the API will work if the request is originated from the domain name/IP you specify. When I don't give it restrictions, the code works, but when I do enter my domain it fails! I entered .mydomainname.com/, the same format as it was suggested, but it errors out somehow.. Now I've got figure out why.

所以,语法没有太大问题!但是我发现在设置 Google API 的“允许的引用者”时问题确实出在后端。使用 V3 API,您可以选择 API 应该属于哪些引用者,因此其他人不能简单地窃取您的 API 并使用它。因此,如果请求源自您指定的域名/IP,则 API 将起作用。当我不给它限制时,代码可以工作,但是当我输入我的域时它会失败!我输入了.mydomainname.com/,与建议的格式相同,但不知何故出错了..现在我已经弄清楚原因了。

回答by Ayush choubey

The following jquery code will fetch the title of the video.

以下 jquery 代码将获取视频的标题。

$.ajax({
      url: "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key="+ apiKey + "&fields=items(snippet(title))&part=snippet", 
      dataType: "jsonp",
      success: function(data){
               console.log(data.items[0].snippet.title);           
      },
      error: function(jqXHR, textStatus, errorThrown) {
          alert (textStatus, + ' | ' + errorThrown);
      }
  });