Вам нужно всего лишь сделать несколько изменений:
- Вместо (
item.title
) используйте (item.snippet.title
) .
- Вместо (
item.id
) используйте (item.id.videoId
) .
- К сожалению, свойство / значение
duration
недоступно в ответе.
Если вы хотите "продолжительность" видео, вы должны использовать (Видео) API.
URL: https://www.googleapis.com/youtube/v3/videos
Проверьте этот пример в API данных YouTube - официальная документация .
Это ответ из приведенного выше примера (вы увидите свойство и значение duration) :
{
"kind": "youtube#videoListResponse",
"etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/8jeHCUnghfiSuxYeP5D9KDIE44Q\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/wMjiWCECcoho_QWk9FLayO8Ipus\"",
"id": "kJQP7kiw5Fk",
"contentDetails": {
"duration": "PT4M42S",
"dimension": "2d",
"definition": "hd",
"caption": "true",
"licensedContent": true,
"projection": "rectangular"
}
}
]
}
Это код с изменениями, которые я сделал для получения значений (videoId
и title
):
// Use your own API KEY here:
var url = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&maxResults=5&key=YOUR_API_KEY"
// The example here will search results about "africa":
$.getJSON(url + "&q=africa", function(json) {
var count = 0;
var html = "";
if (json.items) {
var items = json.items;
items.forEach(function(item) {
// Include the YouTube Watch URL youtu.be
html += '<p><a href="https://youtu.be/' + item.id.videoId + '">';
// Add the default video thumbnail (default quality)
html += '<img src="https://i.ytimg.com/vi/' + item.id.videoId + '/default.jpg">';
// Add the video title and the duration
// N.B, unfortunately, the "duration" property/value is not available in the response.
html += '<h2>' + item.snippet.title + ' - Duration: not available in the response</h2></a></p>';
count++;
});
}
// Add the results in the div called "myDiv".
document.getElementById('myDiv').innerHTML = html;
})
И результаты таковы: