2013-04-05 88 views
0

我想製作一個腳本來獲取特定用戶的最新2上傳在YouTube上的JSON飼料。我試圖用這個腳本從JSON YouTube用戶飼料解析

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script> 
<script type="text/javascript"> 
// Set variables needed for query 
var URL = "https://gdata.youtube.com/feeds/api/users/"; 
var UserName = "MyUsername"; 
var jsonFormat = "/uploads?v=2&alt=jsonc&max-results=2"; 
// Construct the JSON feed of the YouTube user's channel 
var ajaxURL = URL + UserName + jsonFormat; 
// Get the last videos of the YouTube account, parse it into HTML code 
$.getJSON(ajaxURL, function(data){ 
    var htmlString = ""; 

    $.each(data.items, function(i,item){  
     // Here's where we piece together the HTML 
     htmlString += '<iframe class="videos" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/'; 
     htmlString += item.id; 
     htmlString += '?autoplay=0" frameborder="0"></iframe>'; 
    }); 

    // Pop our HTML in the #videos DIV 
    $('#videos').html(htmlString); 

}); 

我一直在使用類似的腳本解析Flickr的JSON和它的正常工作。什麼可能與YouTube的飼料會錯誤?

回答

2

您已將YouTube的API返回到javascript對象data,但請記住,YouTube還會將返回的對象封裝在名爲data的對象中。

因此,在第14行,當你開始通過數據集進行迭代:

$.each(data.items, function(i,item){ 

...實際上應該是:

$.each(data.data.items, function(i,item){ 

這裏是你的代碼(修正)放入jsFiddle:http://jsfiddle.net/Up3W7/

+1

非常感謝,這是一個很好的幫助 – hamama 2013-04-06 05:00:09