Getting title and description of embedded YouTube video

后端 未结 7 1625
抹茶落季
抹茶落季 2021-02-05 12:36

On a site I\'m developing I embed videos from YouTube and want to get the video title and its description.

How do I get that information?

7条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 13:06

    To get the DESCRIPTION element, you need to access the gdata version of the video's info, and you can return json using alt=json on the path. In this case, oHg5SJYRHA0 is the video ID, found at the end of the url of the video you're working with on YouTube, e.g. www.youtube.com/watch?v=oHg5SJYRHA0

    http://gdata.youtube.com/feeds/api/videos/oHg5SJYRHA0?v=2&alt=json&prettyprint=true

    (the prettyprint is formatting to make that easy to read, you don't need it for what you're doing)

    You can grab the JSON, add it into a variable and access it using jQuery:

    var youTubeURL = 'http://gdata.youtube.com/feeds/api/videos/oHg5SJYRHA0?v=2&alt=json';
    var json = (function() {
        var json = null;
        $.ajax({
            'async': false,
            'global': false,
            'url': youTubeURL,
            'dataType': "json",
            'success': function(data) {
                json = data;
            }
        });
        return json;
    })();
    

    Then access it using object notation:

    alert("Title: " + json.entry.title.$t +"\nDescription:\n " + json.entry.media$group.media$description.$t + "\n");
    

提交回复
热议问题