My problem is that it only shows me the first object of the json array but all of them appear in the browser console.
How could I show all those elements that the for returns in text?
<div id="success">
<div id="artistName"></div>
</div>
<script>
$.ajax({
type : 'POST',
url : 'http://ws.audioscrobbler.com/2.0/',
data :'method=artist.gettopalbums&'+'artist=cooldplay&'+api_key=57ee3318536b23ee81d6b27e36997cde&' + 'format=json',
dataType : 'jsonp',
success : function(data) {
for( var i=0 in data.topalbums.album) {
$('#success #artistName').html(data.topalbums.album[i].name);
}
}
});
</script>
What you are doing in it
for
is replacing the codehtml
that is in<div>
each cycle offor
, therefore it only prints the last value. To print all of them, you could do it in the following way.Or you can also do it in the following way and you save lines of code.
What it does
.append()
is that it adds to you, as opposed to.html()
replacing you.This might help you: