Youtube API v3获取上传特定视频的用户的频道ID

时间:2018-12-23 10:39:18

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

我想获取在javascript上上传了某个YouTube视频的用户的频道ID,然后比较该频道ID以查看它是否在数组中。

问题是,我无法确切找到如何从javascript中获取信息。我试图得到:

https://www.googleapis.com/youtube/v3/videos?part=snippet&id=[Video ID]&key=[my key]

但是它给了我每个视频的JSON解析错误。 有人知道如何使用YouTube API完全做到这一点吗?不必在html部分上添加外部脚本。

并且,作为我想做的一个例子,该视频:

https://www.youtube.com/watch?v=jNQXAC9IVRw

它应该返回'UC4QobU6STFB0P71PMvOGN5A'

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我从youmightnotneedjquery.com中提取了Ajax代码,并对其进行了一些编辑,以制作一个getJSON实用程序功能。这对我有用:

var API_KEY = 'YOUR_API_KEY'; // Replace this with your own key

getJSON(
  'https://www.googleapis.com/youtube/v3/videos?part=snippet&id=jNQXAC9IVRw&key=' + API_KEY,
  function (err, data) {
    if (err) {
        alert(err);
    } else {
        alert(data.items[0].snippet.channelId);
    }
  }
);

function getJSON(url, callback) {
  var request = new XMLHttpRequest();
  request.open('GET', url, true);

  request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
      // We have the JSON, now we try to parse it
      try {
        var data = JSON.parse(request.responseText);
        // It worked, no error (null)
        return callback(null, data);
      } catch(e) {
        // A parsing arror occurred
        console.error(e);
        return callback('An error occurred while parsing the JSON.');
      }
    }
    // If an error occurred while fetching the data
    callback('An error occurred while fetching the JSON.');
  };

  request.onerror = function() {
    // There was a connection error of some sort
    callback('An error occurred while fetching the JSON.');
  };

  request.send();
}
相关问题