2011-02-24 29 views
5

一個JSON對象,我最近改變了我的網站設計,現在需要使用動態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> 

有什麼建議嗎?

我想能夠使用JSON對象在整個頁面,這樣,例如,在任何時候我可以叫topartists.artist [I] .playcount;顯示playcount等。我該怎麼做?

+0

http://jsfiddle.net/eSv9x/ – Val 2011-02-24 10:37:52

回答

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

關於你的第二個問題,你需要一個全局變量。您可以在$(document).ready()之前放置它(如註釋中所示),並且無處不在。

+0

感謝瓦爾 - 我知道這將是一些簡單的,但那只是尷尬:) – walden 2011-02-24 14:49:30

0

我嘗試下面的網址,你正在使用的 「http://ws.audioscrobbler.com/2.0/?method=user.getTopArtists &用戶=測試& API_KEY = 690e1ed3bc00bc91804cd8f7fe5ed6d4 &限值爲5 &格式= JSON &回調=?」

它給形成不阱JSON但是,如果使用以下URL 「http://ws.audioscrobbler.com/2.0/?method=user.getTopArtists &用戶=測試& API_KEY = 690e1ed3bc00bc91804cd8f7fe5ed6d4 &限值爲5 &格式= json的」

我得到了正確的JSON。

你也必須聲明html作爲上面給出的響應。