2010-06-03 122 views
0

我正在嘗試使用YouTube的API來恢復用戶視頻的列表。請求網址如下所示:
http://gdata.youtube.com/feeds/api/users/username/uploads
'username'是正確的用戶名。這會在瀏覽器中恢復相應的URL。然而,當我嘗試訪問通過jQuery的$阿賈克斯或$不用彷徨函數,網址,使用類似:jquery ajax vs瀏覽器網址

$.ajax({ 

    //set parameters 
    url: "http://gdata.youtube.com/feeds/api/users/username/uploads", 
    type: "GET", 

    //on success 
    success: function (data) { 
     alert("xml successfully captured\n\n" + data); 
    }, 
    //on error 
    error:function (XMLHttpRequest, textStatus, errorThrown, data){ 
     alert(" We're sorry, there seem to be a problem with our connection to youtube.\nYou can access all our videos here: http://www.youtube.com/user/username"); 
     alert(data); 
    }  
    }); 

    $.get("http://gdata.youtube.com/feeds/api/users/username/uploads", function(data){ 
    alert("Data Loaded: " + data); 
    }); 

我得到一個空文件返回。任何想法,爲什麼這是?

回答

2

你在這裏打same-origin policy,防止跨域請求...但你可以在這種情況下做JSONP之後的事情(因爲youtube支持它,只要JSON數據是你的選項代碼,通常這是首選所以我希望這是你的解決方案)。使用JSONP如下所示:

$.ajax({ 
    url: 'http://gdata.youtube.com/feeds/api/users/username/uploads?alt=json​', 
    dataType: 'jsonp'​​​​, 
    success: function(data) { 
     console.log(data); //entire object here 
     //another example 
     alert("Feed title: " + data.feed.title.$t); 
    } 
});​ 

You can see a working demo here, this grabs the video upload feed for nike。只需探索控制檯中的對象,看看你想要的數據並抓住它:)

+0

非常感謝!然而,我得到了「數據類型:'jsonp'」行後的「意外標記:非法」錯誤... ... – danwoods 2010-06-03 02:51:05

+0

即使我直接複製示例代碼... – danwoods 2010-06-03 02:52:27

+0

沒關係。潛伏在代碼中的一些隱形字符:)再次感謝,我感謝它... – danwoods 2010-06-03 03:17:16