YouTube API - 提取title和videoId属性以构建超链接

时间:2016-06-04 06:37:43

标签: javascript html youtube-api

以下是使用其API搜索YouTube视频数据的JavaScript文件。在底部,你会看到onSearchResponse()函数,它调用showResponse(),然后显示搜索结果。

正如Codecademy的代码所示,与我的搜索字词相关的HUGE信息量会被打印出来。

而不是所有这些,我可以使用标题 videoId 属性显示超链接吗?我将如何在showResponse()中更改responseString以构建该链接?谢谢!

// Your use of the YouTube API must comply with the Terms of Service:
// https://developers.google.com/youtube/terms

// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
    var responseString = JSON.stringify(response, '', 2);
    document.getElementById('response').innerHTML += responseString;
}

// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
    gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}

// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
    // This API key is intended for use only in this lesson.
    // See link to get a key for your own applications.
    gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');

    search();
}

function search() {
    // Use the JavaScript client library to create a search.list() API call.
    var request = gapi.client.youtube.search.list({
        part: 'snippet',
        q: 'clapton'
    });

    // Send the request to the API server,
    // and invoke onSearchRepsonse() with the response.
    request.execute(onSearchResponse);
}

// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
    showResponse(response);
    console.log(response);
}

以下是相应的HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="stylesheets/styles.css">
    <meta charset="UTF-8">
    <title>My YouTube API Demo</title>
</head>
<body>
    <section>
        <div id="response"></div>
    </section>
    <script src="javascripts/search-2.js"></script>
    <script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</body>
</html>

非常感谢您的建议!

1 个答案:

答案 0 :(得分:1)

我认为这可能是你正在努力做的事情。

function showResponse(response) {
  var html = response.items.map(itemToHtml); 
  document.getElementById('response').innerHTML += html;
}

function itemToHtml(item) {
  var title = item.snippet.title;
  var vid = item.id.videoId;
  return generateHyperlink(title, vid);
}

function generateHyperlink(title, vid) {
  return '<a href="https://www.youtube.com/watch?v=' + vid + '">' + title + '</a><br/>';
}

此代码显示名为title的链接,其中包含使用videoId的YouTube视频链接。