2012-02-13 168 views
0

我刚从lastfm和json开始。我可以得到我想要在控制台中返回对象值的信息,但我无法弄清楚为什么我总是得到“undefined”的值。这是我所有的代码。谢谢!lastfm JSON对象返回“undefined”

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html> 
<head> 
    <title>JSON LastFM API Test</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
</head> 
<body> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
    <script type="text/javascript"> 
     $.getJSON("http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist=Bjork&api_key=690e1ed3bc00bc91804cd8f7fe5ed6d4&format=json&callback=?", function(data) { 
      var html = ''; 
      $.each(data.artist, function(i, item) { 
       html += "<p>" + item.name + "</p>"; 
       console.log(data); 
      }); 
      $('#test').append(html); 
     }); 

    </script> 

    <div id="test"></div> 
</body> 

+0

@ZeeTee那应该不重要。 – alex 2012-02-13 04:50:10

回答

1

它出现在JSON返回不是数组。

或许你可以尝试

$.getJSON("http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist=Bjork&api_key="+ apikey+"&format=json&callback=?", function(data) { 
     $('#test').append("<p>" + data.artist.name + "</p>"); 
}); 
+0

感谢ironchefpython。你写的是什么工作,但我继续前进。使用你写的内容帮助我弄清楚如何在需要的情况下编写我的代码。我最后写 $ .getJSON( “http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist=Bjork&api_key=0bd6c5780da878f5bb51393e84329809&format=json&callback=?”,功能(数据){ \t \t \t变种HTML = ''; \t \t \t。每$(数据,功能(I,项目){ \t \t \t HTML + = “

” + data.artist.name + “

”; \t \t \t的console.log (data); \t \t \t}); \t \t \t $('#test')。append(html); \t \t \t}); – heyjohnmurray 2012-02-13 05:05:00

+0

您的'$ .each'在这种情况下是多余的,因为'data'只有一个属性。 – ironchefpython 2012-02-13 05:09:15

+0

是的,这就是我意识到的。谢谢! – heyjohnmurray 2012-02-13 05:14:50

0

如果它只是你想拥有它的名字是在这种情况下很简单:

$.each(data, function(i, item) { 
     html += "<p>" + item.name + "</p>"; 
     html += "<p>" + item.url + "</p>"; 
     console.log(data); 
    }); 
    $('#test').append(html); 

请为我提供一个更复杂的情况下,所以我可以帮助你做到这一点。