获取视频列表youtube api



所以我试图创建一个网络应用程序,当你插入搜索时,它会使用JSON从youtube API获取数据,并呈现一个包含与你的搜索匹配的视频的列表。当它检索时,会得到一些字母和数字答案,但不会得到视频列表。如有任何正确方向的帮助,我们将不胜感激。这就是它的HTML:

<div class="search-box-container">
<form action="#" class="js-search-form search-box">
<label for="query"></label>
<input type="text" class="js-query search-form" placeholder="Search me">
<button type="submit" class="button">Search</button>
</form>
</div>
<h2>Results</h2>
<div class="js-search-results">
</div>

这就是它的JS/Jquery:

const YOUTUBE_SEARCH_URL = 
'https://www.googleapis.com/youtube/v3/search';
`const key = 'key'//(hidden for privacy concerns);`
function getDataFromApi(searchTerm, callback) {
const query = {
part: 'snippet',
key: key,
q: `${searchTerm} in:name`,
}
$.getJSON(YOUTUBE_SEARCH_URL, query, callback);
}
function renderResult(result) {
return `
<div>
<h2>
<a class="js-result-name" href="http//www.youtube.com/watch?v=${ 
result.id.videoId}" target="_blank">${result.id.videoId}</a></h2>
</div>
`;
}
function displayYoutubeSearchData(data) {
console.log(data);
const results = data.items.map((item, index) => renderResult(item));
$('.js-search-results').html(results);
}
function watchSubmit() {
$('.js-search-form').submit(event => {
event.preventDefault();
const queryTarget = $(event.currentTarget).find('.js-query');
const query = queryTarget.val();
queryTarget.val("");
getDataFromApi(query,displayYoutubeSearchData );
});
}

$(watchSubmit);

这是得到的答案

你几乎做到了:这只是一个拼写错误。

查看renderResult()方法返回的模板文字中的href属性。

href="http//www.youtube.com/watch?v=${result.id.videoId}"

注意格式错误的方案(http//https://(。

一点上下文:

YouTube API返回与API请求中指定的查询参数匹配的搜索结果集合(即对象数组,代码中的data.items(。

每个项都包含一个具有videoId属性的id对象。这就是你在问题中提到的">字母数字答案"。将data.items映射到一个resultHTML模板数组后,您就可以使用${result.id.videoId}读取该视频id。然后将YouTube观看的URL与视频id连接起来。

您应该在YouTube数据API文档中检查搜索结果的JSON结构。除了id.videoId,它还包含了更多有用的信息。例如,您可能更喜欢使用${result.snippet.title}而不是字母数字videoId向用户显示视频的标题。

最新更新