使onYouTubeIframeAPIReady()在Ajax成功回调中工作



我正在通过Ajax从我的DB中获取视频数据,我需要在Ajaxsuccess回调中加载播放器中的YouTube视频。

在Ajax之外,onYouTubeIframeAPIReady()运行良好。但在Ajax内部,它不起作用。没有错误,似乎没有开火。

这是我的全部代码:

// HTML
<div id="player"></div>
// JS
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player, video;
$('.content').on('click', '.view', function() {
video = $(this).data('id');

$.ajax({
type: 'POST',
url: '/scripts/video-view.php',
dataType: 'json',
data: {video_id:video},
success: function(data) {
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
playerVars: {
'modestbranding': 1
}
});
}
}
});
});

有什么想法为什么它在Ajax成功回调中不起作用吗?

第页。S.我通过Ajax需要它的原因是动态加载videoId和一些playerVars。videoId是上述示例中用于演示目的的静态值。在live中,它是从数据库中检索的动态值。此外,我正在实时服务器上测试,而不是在本地主机上。

我似乎找到了一种方法。这可能不是最好或理想的方法,但它似乎能完成我需要它做的大部分事情。

// HTML
<div id="player"></div>
// JS
var player, 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() {
player = new YT.Player('player', {
height: '390',
width: '640',
playerVars: {
'fs': 0,
'modestbranding': 1,
'playsinline': 1
}
});
}
$('.content').on('click', '.view', function() {
videoId = $(this).data('id');

$.ajax({
type: 'POST',
url: '/scripts/video-view.php',
dataType: 'json',
data: {video_id:videoId},
success: function(data) {
player.loadVideoById({'videoId':data.id, 'startSeconds':data.start});
}
});
});

Ajax返回data.id作为视频id,返回data.start作为视频开始时间。以上设置对于从DB检索的动态视频id和开始时间来说已经足够了。我想我可以接受静态playerVars值。

我暂时不会将此标记为已接受的答案,以防其他人发布更好的解决方案。

最新更新