我使用以下代码首先从我的Youtube API获得视频Id,然后使用Youtube Media API在我的页面上加载媒体播放器:
var qval = <?php echo "'{$name}'" ;?>;
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(loadAPIClientInterfaces, 1);
});
}
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', searchData);
}
function searchData() {
var request = gapi.client.youtube.search.list({
key : "My_app_ID",
q : qval,
part : 'snippet',
maxResults : 5
});
request.execute(function(response) {
console.log(response);
console.log(response['items'][1]['id']['videoId']);
onYouTubeIframeAPIReady(response['items'][1]['id']['videoId']);
});
}
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady(vid) {
var newDiv = document.createElement('div');
newDiv.setAttribute('id','newDiv');
var prev = document.getElementById('player');
prev.appendChild(newDiv);
console.log(vid);
player = new YT.Player('newDiv', {
height: '390',
width: '640',
videoId : vid
});
}
它没有加载播放器,即使在调试函数onYouTubeIframeAPIReady() vid加载一个值,我可以直接在youtube链接中使用来获取视频
做了一些改变,它变得很好:
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(loadAPIClientInterfaces, 1);
});
}
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', searchData);
}
function searchData() {
var qval=<?php echo "'{$name}'" ;?> ;
var request = gapi.client.youtube.search.list({
key : "my_app_key",
q : qval,
part : 'snippet',
maxResults : 5
});
request.execute(function(response) {
console.log(response);
for(var i = 0; i < response['items'].length;i++){
console.log(response['items'][i]['id']['videoId']);
var newDiv = document.createElement('div');
var prev = document.getElementById('player');
prev.appendChild(newDiv);
onYouTubeIframeAPIReady(response['items'][i]['id']['videoId'],newDiv);
}
});
}
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady(vid,newDiv) {
if (typeof vid != 'undefined'){
player = new YT.Player(newDiv, {
height: '390',
width: '640',
videoId : vid
});
} else {
console.log(vid);
}
}