使用带有Last.FM API的jQuery $ .ajax创建/访问JSON对象

wal*_*den 5 ajax jquery json last.fm

我最近改变了我的网站设计,现在需要对我的数据使用动态AJAX请求.基本上,我正在尝试使用JSON格式的Last.FM API检索用户数据.

我对此很新,特别是JSON,它让我有点头疼!我知道我一定会错过一些简单的事情.

这是一些非常基本的代码来测试功能,但它没有检索任何东西!

<html>
<head>
    <script src="./jquery/jquery-1.4.4.js"></script>  
</head>
<body>
<script type="text/javascript">

$(document).ready(function() {  
    $.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getTopArtists&user=test&api_key=690e1ed3bc00bc91804cd8f7fe5ed6d4&limit=5&format=json&callback=?", function(data) {
        $.each(data.topartists.artist, function(i,item){
            html += "<p>" + item.name + " - " + item.playcount + "</p>";    
        });
        $('#test').append(html);
    });
});
</script>

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

</body></html>
Run Code Online (Sandbox Code Playgroud)

有什么建议?

我希望能够在整个页面中使用JSON对象,例如,在任何时候我都可以调用topartists.artist [i] .playcount; 显示playcount等.我该怎么做?

Val*_*Val 3

html 变量必须在以下范围之外声明each

  //var topArt;
 $(document).ready(function() {
    $.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getTopArtists&user=test&api_key=690e1ed3bc00bc91804cd8f7fe5ed6d4&limit=5&format=json&callback=?", function(data) {
        var html = '';
        $.each(data.topartists.artist, function(i, item) {
            html += "<p>" + item.name + " - " + item.playcount + "</p>";
        });
        $('#test').append(html);
         // topArt = data.topartists;
    });
});
Run Code Online (Sandbox Code Playgroud)

至于你的第二个问题,你需要一个全局变量。您可以将其放在前面$(document).ready()(如评论中所示),这样就可以在任何地方访问它。