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

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

问题描述

我正在尝试显示基于 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.

到目前为止我已经使用了以下代码,它确认我在控制台中成功加载了对象-

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

任何帮助将不胜感激.谢谢!

Any help would be much appreciated. Thanks!

更新了下面的代码,这有效:

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 数组已经解析)

(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

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

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