javascript - 使用 Youtube V3 API 和 JavaScript 获取 Youtube 视频 URL

标签 javascript youtube-javascript-api youtube-data-api

我对此主题进行了大量搜索,但我只能找到与 Youtube API V2 相关的资源,该资源也没有贬值。

我想要做的是使用 Javascript 从 Youtube V3 API URL 的 JSON 响应中获取 Youtube 视频标题、缩略图和链接。

我运行下面的代码,但收到错误消息Uncaught TypeError:无法读取未定义的属性“items”

    <input id="searchquery" />
<div id="results"></div>

<!-- Include the latest jQuery library -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<script type="text/javascript">
jQuery(document).ready(function ($) {

  $('#searchquery').keyup(function () {

    // the search term
    var q = $('#searchquery').val().trim();

    // container to display search results
    var $results = $('#results');

    // YouTube Data API base URL (JSON response)
    var url = "https://www.googleapis.com/youtube/v3/search?part=snippet&order=date&key=AIzaSyC3TJRI1C0EVEdl7b19InH1gv9yrAOX2YU"


    url = url + '&max-results=50';

    $.getJSON(url + "&q=" + q, function (json) {

      var count = 0;

      if (json.data.items) {

        var items = json.data.items;
        var html = "";

        items.forEach(function (item) {

          // Check the duration of the video, 
          // full-length movies are generally longer than 1 hour
          var duration = Math.round((item.duration) / (60 * 60));

          // Filter out videos that aren't in the Film or Movies category
          if ((duration > 1) && (item.category == "Movies" || item.category == "Film")) {

            // Include the YouTube Watch URL youtu.be 
            html += '<p><a href="http://youtu.be/' + item.id + '">';

            // Add the default video thumbnail (default quality)
            html += '<img src="http://i.ytimg.com/vi/' + item.id + '/default.jpg">';

            // Add the video title and the duration
            html += '<h2>' + item.title + ' ' + item.duration + '</h2></a></p>';
            count++;
          }
        });
      }

      // Did YouTube return any search results?
      if (count === 0) {
        $results.html("No videos found");
      } else {
        // Display the YouTube search results
        $results.html(html);
      }
    });
  });
});
</script>

我的网址是 https://www.googleapis.com/youtube/v3/search?part=snippet&order=date&key=AIzaSyC3TJRI1C0EVEdl7b19InH1gv9yrAOX2YU&q=opencourseware

这会返回

{
 "kind": "youtube#searchListResponse",
 "etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/anQeVHiFN6CH_dx-tP89Q8heOos\"",
 "nextPageToken": "CAUQAA",
 "pageInfo": {
  "totalResults": 24815,
  "resultsPerPage": 5
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/4DMiUQkDt0Bic4cV0lZbi7KZ1tk\"",
   "id": {
    "kind": "youtube#playlist",
    "playlistId": "PL-4XVpiAbrw8bRUhUHfm-omUYAyBepYiB"
   },
   "snippet": {
    "publishedAt": "2015-09-01T06:23:39.000Z",
    "channelId": "UCOY4GuDhH3KHVcpZqD5S87w",
    "title": "Popular Videos - Bioinformatics & OpenCourseWare",
    "description": "",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/R-PjAS8d1_0/default.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/R-PjAS8d1_0/mqdefault.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/vi/R-PjAS8d1_0/hqdefault.jpg"
     }
    },
    "channelTitle": "",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/-D3XCQyB-podnhbL-keBQoIZMb8\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "vOpp8nOp9uA"
   },
   "snippet": {
    "publishedAt": "2015-08-10T09:27:38.000Z",
    "channelId": "UCBL-6EKd9b1DW73ZcY-PNcw",
    "title": "Audio OpenCourseWare",
    "description": "OpenCourseWare dilaksanakan pada tanggal 10 Juli 2015 di Ruang Video Conference, Gedung D, Lantai 2 Direktorat Sistem Informasi, Telkom University ...",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/vOpp8nOp9uA/default.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/vOpp8nOp9uA/mqdefault.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/vi/vOpp8nOp9uA/hqdefault.jpg"
     }
    },
    "channelTitle": "",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/hwBjyzzUi0M3qf0QKR6EvAD6RTs\"",
   "id": {
    "kind": "youtube#playlist",
    "playlistId": "PL2Co6UkQCJCrvFuM-KEY6Pfccm2PKNhGe"
   },
   "snippet": {
    "publishedAt": "2015-08-03T21:28:26.000Z",
    "channelId": "UCqHlUWMIi07M5U6kVSJT7RA",
    "title": "Popular Videos - OpenCourseWare & Teacher",
    "description": "",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/SQI2I48QUBQ/default.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/SQI2I48QUBQ/mqdefault.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/vi/SQI2I48QUBQ/hqdefault.jpg"
     }
    },
    "channelTitle": "",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/igp-ZANLFmAQxfuTsPHpNeJwdwg\"",
   "id": {
    "kind": "youtube#playlist",
    "playlistId": "PLfu3FYNDydnC8bAZrkXpFXXxbCE8O9ZYS"
   },
   "snippet": {
    "publishedAt": "2015-07-07T15:38:00.000Z",
    "channelId": "UCqL4K9FRJ90uHEvRsSXi5cA",
    "title": "Popular Videos - MIT OpenCourseWare & Field",
    "description": "",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/PgE9oBDIgdc/default.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/PgE9oBDIgdc/mqdefault.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/vi/PgE9oBDIgdc/hqdefault.jpg"
     }
    },
    "channelTitle": "",
    "liveBroadcastContent": "none"
   }
  },
  {
   "kind": "youtube#searchResult",
   "etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/9G1cGWzCiMxuc7L_KpgWTyJFjzk\"",
   "id": {
    "kind": "youtube#playlist",
    "playlistId": "PL2Co6UkQCJCp_IpNmpim5CPhKC0gE95jv"
   },
   "snippet": {
    "publishedAt": "2015-06-19T21:28:19.000Z",
    "channelId": "UCqHlUWMIi07M5U6kVSJT7RA",
    "title": "Popular Videos - OpenCourseWare & Educational Technology",
    "description": "",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/ad4oFCHBSRQ/default.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/ad4oFCHBSRQ/mqdefault.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/vi/ad4oFCHBSRQ/hqdefault.jpg"
     }
    },
    "channelTitle": "",
    "liveBroadcastContent": "none"
   }
  }
 ]
}

最佳答案

将 json.data.items 更改为 json.items

关于javascript - 使用 Youtube V3 API 和 JavaScript 获取 Youtube 视频 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32410837/

相关文章:

javascript - 在xml中调用php变量

c# - 如何将 JavaScript double 组转换为 .NET double 组?

javascript - 在现有 Canvas 内的多边形中添加 HTMLImageElement

javascript - youtube 视频暂停时触发事件

php - 通过refresh_token获取新的access_token非常不可靠

javascript - 隐藏包含空列的行

javascript - 如何将 YouTube API 持续时间(格式为 PT#M#S 的 ISO 8601 持续时间)转换为秒

youtube - 嵌入只有播放、暂停和刷新按钮的 youtube 视频

c# - Youtube Live API - 使用 OAuth 拒绝广播权限

google-api - 在 Google API 的 OAuth 中为客户端 ID 选择 'Other' 的选项不可用