解析JSON对象的HTML表 [英] Parsing JSON objects for HTML table

查看:188
本文介绍了解析JSON对象的HTML表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于JSON数据显示排行榜表。

I am trying to display a "leaderboard" table based on JSON data.

我已经阅读了很多关于JSON格式,克服一些初步的障碍,但我的JavaScript的知识是非常有限的,我需要帮助!

I have read a lot about the JSON format and overcome some initial obstacles, but my Javascript knowledge is very limited and I need help!

基本上我的JSON数据均通过寻找这样的:

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.

到目前为止,我已经用下面的code,这证实了我成功加载在控制台 - 对象

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);
});

但我不知道如何遍历它们,把它们解析成HTML表格。

but I am not sure how to iterate over them, parsing them into the HTML table.

下一步是排序以降序由得分的条目...

The next step is sorting the entries by score in descending order...

任何帮助将是非常美联社preciated。
谢谢!

Any help would be much appreciated. Thanks!

编辑:

下面更新code,这个作品:

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没有必要,我们可以用数据作为JSON数组已经解析我相信)

(The $.parseJSON was not necessary, we can use 'data' as the JSON array is already parsed I believe)

推荐答案

遍历每个对象,添加一个表行的相关数据每一次迭代。

Loop over each object, appending a table row with the relevant data each iteration.

$(document).ready(function () {
    $.getJSON(url,
    function (json) {
        var tr;
        for (var i = 0; i < json.length; i++) {
            tr = $('<tr/>');
            tr.append("<td>" + json[i].User_Name + "</td>");
            tr.append("<td>" + json[i].score + "</td>");
            tr.append("<td>" + json[i].team + "</td>");
            $('table').append(tr);
        }
    });
});

的jsfiddle

这篇关于解析JSON对象的HTML表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆