使用JSON从Youtube获取信息无法在FIREFOX中使用

时间:2013-01-09 09:45:29

标签: javascript json youtube youtube-api

我正在尝试通过JSON从Youtube获取数据。此代码在Chrome中运行良好,但在Firefox中无效。我的代码如下:

function test(url){

  var youtube_id = url.replace(/^[^v]+v.(.{11}).*/,"$1");
  var video_id= youtube_id;
    $.get('http://gdata.youtube.com/feeds/api/videos/'+video_id+'?v=2&alt=json', function(data) {
    var title = data.entry.title.$t;
    var description = data.entry.media$group.media$description.$t;
    var thumbnail = data.entry.media$group.media$thumbnail[0].url; // URL of the image

   document.writeln(thumbnail);
   document.writeln(description);// Use these variables somewhere
});
}

  

提前致谢 - 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您需要为ajax请求指定数据类型,以使其在firefox和chrome中运行。 Chrome会自动解析JSON以获得成功回调,而Firefox则不会。

这样:

function test(url){

  var youtube_id = url.replace(/^[^v]+v.(.{11}).*/,"$1");
  var video_id= youtube_id;
    $.get('http://gdata.youtube.com/feeds/api/videos/'+video_id+'?v=2&alt=json', function(data) {
    var title = data.entry.title.$t;
    var description = data.entry.media$group.media$description.$t;
    var thumbnail = data.entry.media$group.media$thumbnail[0].url; // URL of the image

   document.writeln(thumbnail);
   document.writeln(description);// Use these variables somewhere
}, "json");
}

适合我。

这是一个适用于chrome和firefox的jsfiddle:http://jsfiddle.net/8dyWr/1

和get方法签名:

jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

来自:http://api.jquery.com/jQuery.get/