我正在try 显示一个基于JSON数据的"排行榜"表.
我读了很多关于JSON格式的书,并克服了一些最初的障碍,但我的Javascript知识非常有限,我需要帮助!
Basically my JSON data comes through looking like this:
[{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}]
What I need is to be able to loop through this array, generating a table row or list item for each object. There will be an unknown amount of total objects in the array but each will have the same format- three values: Name, Score, Team.
So far I have used the following code, which confirms that I am successfully loading the objects in the console-
$.getJSON(url,
function(data){
console.log(data);
});
but I am not sure how to iterate over them, parsing them into the HTML table.
下一步是按分数降序对条目进行排序.
任何帮助都将不胜感激.
EDIT:
Updated code below, this works:
$.getJSON(url,
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].User_Name + "</td>");
tr.append("<td>" + data[i].score + "</td>");
tr.append("<td>" + data[i].team + "</td>");
$('table').append(tr);
}
});
(没有必要使用$.parseJSON,我们可以使用'data',因为我相信JSON数组已经被解析了)