jquery ajax vs浏览器网址

时间:2010-06-03 02:17:42

标签: jquery ajax api get youtube

我正在尝试使用youtube的api来恢复用户视频的列表。请求网址如下所示:
    http://gdata.youtube.com/feeds/api/users/username/uploads
'username'是正确的用户名。这会在浏览器中返回相应的URL。但是,当我尝试通过jQuery的$ .ajax或$ .get函数访问该URL时,使用类似的东西:

$.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);
  });

我收到一份空文件。任何想法为什么会这样?

1 个答案:

答案 0 :(得分: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。只需在控制台中浏览对象以查看您想要的数据并抓住它:)

相关问题