【问题标题】:Get list of videos youtube api获取视频列表 youtube api
【发布时间】:2019-04-04 02:17:15
【问题描述】:

所以我正在尝试创建一个网络应用程序,当您插入搜索时,它会使用 JSON 从 youtube API 获取数据,并呈现一个包含与您的搜索匹配的视频的列表。当它检索时,它会得到一些字母和数字答案,但不是视频列表。任何正确方向的帮助将不胜感激。这是它的 HTML:

     <div class="search-box-container">
     <form action="#" class="js-search-form search-box">
      <label for="query"></label>
      <input type="text" class="js-query search-form" placeholder="Search me">
      <button type="submit" class="button">Search</button>
    </form>
  </div>

  <h2>Results</h2>

  <div class="js-search-results">

  </div>

这就是它的 JS/Jquery:

  const YOUTUBE_SEARCH_URL = 
'https://www.googleapis.com/youtube/v3/search';
`const key = 'key'//(hidden for privacy concerns);`

function getDataFromApi(searchTerm, callback) {
 const query = {
  part: 'snippet',
  key: key,
  q: `${searchTerm} in:name`,
 }
  $.getJSON(YOUTUBE_SEARCH_URL, query, callback);
}

function renderResult(result) {
 return `
  <div>
   <h2>
   <a class="js-result-name" href="http//www.youtube.com/watch?v=${ 
   result.id.videoId}" target="_blank">${result.id.videoId}</a></h2>
  </div>
 `;
}

function displayYoutubeSearchData(data) {
 console.log(data);
 const results = data.items.map((item, index) => renderResult(item));
 $('.js-search-results').html(results);
}

function watchSubmit() {
 $('.js-search-form').submit(event => {
  event.preventDefault();
  const queryTarget = $(event.currentTarget).find('.js-query');
  const query = queryTarget.val();
  queryTarget.val("");
  getDataFromApi(query,displayYoutubeSearchData );
 });
}


$(watchSubmit);

This is the answer that gets rendered

【问题讨论】:

  • 你能发布一个你得到的答案的例子吗?
  • 嗨大卫,我发布了我在搜索时得到的答案
  • @Gianina 我猜你已经在点击它时获得了链接,它会重定向到 youtube,不是吗?
  • @VineyHill 不确定我得到了什么,因为单击它会重定向到“未找到”
  • 你得到的是 video id 例如。 RnBT9uUYb1w ---> youtube.com/watch?v=RnBT9uUYb1w 这是一个有效的视频。所以你只需要使用它们来组成链接。如果你想嵌入它们然后前往youtubevideoembed.com自定义方式然后你想在你的代码中使用 html。

标签: javascript json ajax forms youtube-api


【解决方案1】:

你快到了:这只是一个错字。

查看renderResult() 方法返回的模板文字内的href 属性。

href="http//www.youtube.com/watch?v=${result.id.videoId}"

注意格式错误的方案(http// vs https://)。

一点上下文:

YouTube API 返回与 API 请求中指定的查询参数匹配的搜索结果集合(即对象数组,代码中的 data.items)。

每个项目都包含一个带有videoId 属性的id 对象。这就是您在问题中提到的“字母数字答案”。在将data.items 映射到result HTML 模板数组之后,您正在读取带有${result.id.videoId} 的视频ID。然后将 YouTube watch URL 与视频 ID 连接起来。

您应该检查YouTube Data API docs 中搜索结果的JSON 结构。除了id.videoId,它还包含更多有用的信息。例如,您可能更愿意使用${result.snippet.title} 而不是字母数字videoId 向用户显示视频的标题。

【讨论】:

  • 谢谢你,这就是我想要展示的,由 url 检索到的标题。我想它可能正在检索正确的 ingo (videoId) 但我需要的是标题
  • @GianinaSkarlett - 你明白了吗?链接是否有效?你得到了${result.snippet.title}的标题吗?
  • 非常感谢!我做到了。现在我正在用它来渲染缩略图!
  • @GianinaSkarlett - 欢迎您!缩略图位于${result.snippet.thumbnails}。我认为您可以使用${result.snippet.thumbnails.default.url} 获得默认值。
  • 谢谢@David!我会让你知道情况如何!
猜你喜欢
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 2014-11-20
  • 2017-09-01
  • 2012-12-06
  • 2012-10-24
  • 2015-12-03
  • 2017-08-25
相关资源
最近更新 更多