0

我使用Youtube Iframe API和使用他們的腳本玩家加載罰款。但是,當我做一個Ajax調用包含JavaScript代碼的php文件來運行播放器時,它不會執行。Javascript無法在AJAX後

function get_content(song_id,url,song_title) { 
if (song_id == null) 
    return; 
    document.title = song_title + browser_title_suffix; 
    $.get('/ajax/player.php',{song_id:song_id}, function(data) { 
     $('#main_content').html(data).css({'opacity':0}).animate({'opacity':1}); 
     }); 
     } 

/ajax/player.php包含此代碼 - https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player

然而,玩家不試。我甚至嘗試過player.remove(),但那也沒有幫助。

更新1: 我的PHP文件:

var tag = document.createElement('script'); 
tag.src = "//www.youtube.com/iframe_api"; 
var firstScriptTag = document.getElementsByTagName('script')[0]; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

$(document).ready(function(){ 
get_content('.$row[song_id].',null,"'.$row[title].'"); 
}); 

</script> 

我的JavaScript文件:

function get_content(song_id,url,song_title) { 
if (song_id != null) { 
    $.get('/ajax/player.php',{song_id:song_id}, function(data) { 
     video_id = data; 
     player = new YT.Player('player', { 
      height: '390', 
      width: '640', 
      videoId: video_id, 
      events: { 
       'onReady': onPlayerReady, 
       'onStateChange': onPlayerStateChange 
      } 
     }); 
    }); 

} 
} 

但是,視頻播放器不加載。

+1

他在控制檯中的任何東西? PHP加載後是否直接顯示正確的數據? – mplungjan 2013-02-10 09:36:18

+0

不,控制檯中什麼都沒有,當php第一次加載數據時,它一切正常。這是當我想加載新的內容,它不起作用。 – goldenboy48 2013-02-10 10:02:53

回答

0

您無法通過ajax獲取javascript,然後運行剛收到的javascript。你想要做的就是通過AJAX發送YouTube視頻ID,然後使用這樣的函數來放置玩家:

function get_content(song_id,url,song_title) { 
    if (song_id != null) { 
     $.get('/ajax/player.php',{song_id:song_id}, function(data) { 
      video_id = data; 

      player = new YT.Player('player', { 
       height: '390', 
       width: '640', 
       videoId: video_id, 
       events: { 
        'onReady': onPlayerReady, 
        'onStateChange': onPlayerStateChange 
       } 
      }); 
     }); 
    } 
} 

更重要的是,試圖通過JSON jQuery來發送和收到的數據。

+0

嘿,謝謝你的回覆。我遵循了你的建議,但不會觸發玩家加載。我在** UPDATE 1中發佈了更新**我在控制檯中得到以下錯誤:未捕獲的ReferenceError:未定義YT – goldenboy48 2013-02-10 23:45:28

+0

那麼,確保它已被定義,因爲您使用它...沒有足夠的代碼給我們進一步幫助。 – 2013-02-11 00:10:18