我最近更改了网站设计,现在需要对我的数据使用动态 AJAX 请求。基本上,我尝试使用 Last.FM API 以 JSON 格式检索用户数据。
我对此很陌生,尤其是 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;显示播放次数等。我该怎么做?
最佳答案
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()
之前(如注释所示),这样就可以在任何地方访问它。
关于jquery - 使用 jQuery $.ajax 和 Last.FM API 创建/访问 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5103356/