Creating/Accessing a JSON object using jQuery $.ajax with Last.FM API

巧了我就是萌 提交于 2019-11-29 22:04:52

问题


I've recently changed my site design and now need to use dynamic AJAX requests for my data. Basically, I'm trying to retrieve user data using the Last.FM API in JSON format.

I'm newish to this, particularly JSON, and it's giving me a bit of a headache! I know I must be missing something simple.

Here is some very basic code to test the functionality but it's not retrieving anything!

<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>

Any suggestions?

I would like to be able to use the JSON object throughout the page so, for example, at any time I can just call topartists.artist[i].playcount; to display the playcount, etc. How can I do this?


回答1:


The html variable must be declared outside the scope of the 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;
    });
});

As for your second question, you'll need a global variable. You can put it before $(document).ready() (as shown in the comment) and it will be accessible everywhere.




回答2:


I tried the following URL what you are using "http://ws.audioscrobbler.com/2.0/?method=user.getTopArtists&user=test&api_key=690e1ed3bc00bc91804cd8f7fe5ed6d4&limit=5&format=json&callback=?"

It gives not-well-formed json but if I use following URL "http://ws.audioscrobbler.com/2.0/?method=user.getTopArtists&user=test&api_key=690e1ed3bc00bc91804cd8f7fe5ed6d4&limit=5&format=json"

I got the correct JSON.

Also you'll have to declare html as the response given above.



来源:https://stackoverflow.com/questions/5103356/creating-accessing-a-json-object-using-jquery-ajax-with-last-fm-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!