So I'm using AJAX to scrape player names and their respective ratings from a site. I have AJAX return a JSON object and I'm trying to use jQuery to append each element of the JSON object as a list item in an ordered list.
Here's the code:
$('#rankings_link').click(function(){
$.ajax({
dataType: 'json',
url: '/rankings',
type: 'get'
}).done(function(received_data){
for (var m = 0; m < received_data.length; m++) {
$('#rankings ol').append('<li>' + received_data[m] + '</li>');
}
But when I look at my localhost:3000/rankings page, it's just one large array of player names (correctly ordered) but not formatted as a list at all.
What's going on here?
Thanks in advance, Mariogs
http://www.w3schools.com/json/json_eval.asp
I would use eval to get you json string into an object you can loop an array through
var rankings = eval ("(" + received_data + ")");
for (var m = 0; m < rankings.length; m++) {
$('#rankings ol').append('<li>' + rankings[m].(whatever piece of data you want from your json object) + '</li>');
}
If you are still having trouble show me what your json string looks like.
I would use a $.each loop to sort thru the received data. The json object is an unordered set of key/value pairs. When you use a $.each loop you can separate those out and utilize the value(player info) which is what you are looking for. Like this:
$('#rankings_link').click(function(event){
event.preventDefault();
$.ajax({
dataType: 'json',
url: '/rankings',
type: 'get'
}).done(function(received_data){
$.each(received_data, function(index, player){
$('#rankings ol').append('<li>' + player + '</li>');
});
});
});