使用 JSON 对象数据填充 html table

Populating html table with JSON object data

我正在从 fileUpload 控件获取一个 csv 文件,并将 csv 文件也转换为 JSON 对象。现在我试图用这个 JSON 数据填充 html table。我写了一个 populatetable() 函数,但它没有正确显示数据。 CSV 到 JSON 的转换正在正常进行,如下所示 - JSON object

HTML 文件:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"> </script>
    <!--<script type="text/javascript" src="JavaScript.js"></script>-->
    <script type="text/javascript" src="CSV_to_JSON.js"></script>


    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
        }

        th, td {
            padding: 15px;
        }

        th {
            text-align: left;
        }

        table {
            border-spacing: 5px;
        }

        .guide {
            text-decoration: underline;
            text-align: center;
        }

        .odd {
            color: #fff;
            background: #666;
        }

        .even {
            color: #666;
        }

        .hot {
            border: 1px solid #f00;
        }
    </style>

</head>
<body>

    <div class="container">
        <div class="row">
            <h2>---</h2>
        </div>
        <div class="panel panel-primary">
            <div class="panel-heading">---</div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-sm-12 col-sm-offset-1">

                        <form id="form1" runat="server" class="form-horizontal">
                            <div class="form-group">
                                <div class="col-sm-5">
                                    <div class="col-sm-6">
                                        <input type="file" accept=".csv" id="fileUpload" />
                                    </div>
                                    <div class="col-sm-6">
                                        <input type="button" id="upload" class="btn btn-primary" value="Upload" />
                                    </div>

                                </div>
                                <div class="col-sm-7">
                                    <div class="col-sm-2">
                                        <input type="button" id="cancel" class="btn btn-primary btn pull-right" value="Cancel/Save" style="visibility: hidden" />
                                    </div>
                                    <div class="col-sm-2">
                                        <input type="button" id="process" class="btn btn-primary btn pull-right" value="Process" style="visibility: hidden" />
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-12">
                        <div class="panel panel-default" style="align-self: center">
                            <div class="panel-body" style="max-height: 400px; min-height: 400px; overflow-y: scroll;">
                                <div class="row">
                                    <div class="col-sm-12">
                                        <center>
                                                        <div class="input-append" id="filterDev" style="visibility:hidden">
                                                          <input name="search" id="inputFilter" placeholder="Enter ID to filter" />
                                                             <input type="button" value="Filter" id="filter" class="btn btn-primary" />
                                                                </div></center>
                                    </div>
                                    <br />
                                    <br />

                                </div>
                                <div class="row">
                                    <div class="col-sm-12" id="dvCSV"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-12">
                        <p id="download" style="color: cornflowerblue; visibility: hidden"><strong>Please click the below links to download the processed file..</strong></p>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <div class="col-sm-3">
                            <p id="File1" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File1 Download</p>
                        </div>
                        <div class="col-sm-3">
                            <p id="File2" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File2 Download</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


</body>
</html>
<script type="text/javascript">

    $("#cancel").on("click", function () {
        $('input:checked').each(function () {
            $(this).closest("tr").remove();
        });
    });

    /*$('#inputFilter').keyup(function () {
        var that = this;
        $.each($('tr'),
        function (i, val) {
            if ($(val).text().indexOf($(that).val()) == -1) {
                $('#name').animate({
                    marginTop: 0
                },
                50,
                function () {
                    $('tr').eq(i).hide();
                });
            } else {
                $('#name').animate({
                    marginTop: 0
                },
                50,
                function () {
                    $('tr').eq(i).show();
                });
            }
        });
    });*/

    $(function () {
        $("#process").bind("click", function () {

            document.getElementById("File1").style.visibility = "visible";
            document.getElementById("File2").style.visibility = "visible";
            document.getElementById("download").style.visibility = "visible";

        });

    });

</script>

CSV_to_JSON.js -

$(function () {
    $("#upload").bind("click", function () {

        var regex = /^([a-zA-Z0-9\s_\.\-:])+(.csv|.txt)$/;
        if (regex.test($("#fileUpload").val().toLowerCase())) {
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function (e) {
                    //var table = $("<table id='name'/>");
                    var lines = e.target.result.split("\n");
                    var result = [];
                    var headers = lines[0].split(",");
                    //alert(headers);

                    for (var i = 1; i < lines.length; i++) {
                        var obj = {};
                        var currentline = lines[i].split(",");

                        for (var j = 0; j < headers.length; j++) {
                            obj[headers[j]] = currentline[j];
                        }
                        result.push(obj);
                    }
                    alert(JSON.stringify(result));
                    populateTable(JSON.stringify(result));
                }
                reader.readAsText($("#fileUpload")[0].files[0]);
            }
        }

    });
});

function populateTable(object) {

    var obj = object;
    var table = $("<table />");
    table[0].border = "1";
    var columnCount = obj[0].length;
    var row = $(table[0].insertRow(-1));

    for (var i = 0; i < columnCount; i++) {
        var headerCell = $("<th />");
        headerCell.html(obj[0][i]);
        row.append(headerCell);
    }

    for (var i = 1; i < obj.length; i++) {
        row = $(table[0].insertRow(-1));
        for (var j = 0; j < columnCount; j++) {
            var cell = $("<td />");
            cell.html(obj[i][j]);
            row.append(cell);
        }
    }

    var dvTable = $("#dvCSV");
    dvTable.html("");
    dvTable.append(table);

}

如何在 html table 中正确显示此数据?

问题源于您如何从 JSON object 获取密钥。 object 没有 length 属性 并且如果不在 object 之一上调用 Object.keys() 就不能像数组一样直接遍历它的键小号::

var columns = Object.keys(obj[0]);
// gives ["ID","Name","City","Address","Designation"]

从那里您可以获得列长度并参考列数组来设置您的 header 行:

var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
    var headerCell = $("<th />");
    headerCell.html([columns[i]]);
    row.append(headerCell);
}

您还需要修改设置后续 table 行的循环,以便在为每一行创建每个单元格时查找列名:

for (var i = 0; i < obj.length; i++) {
    row = $(table[0].insertRow(-1));
    for (var j = 0; j < columnCount; j++) {
        var cell = $("<td />");
        cell.html(obj[i][columns[j]]);
        row.append(cell);
    }
}

这是一个带有一些模拟数据的演示:

var mockData = [{
  "ID": 1,
  "Name": "Kevin",
  "City": "Santa Clara",
  "Address": "Longmen",
  "Designation": "VP Marketing"
}, {
  "ID": 2,
  "Name": "Tina",
  "City": "São Bartolomeu",
  "Address": "Bojongloa",
  "Designation": "Computer Systems Analyst III"
}, {
  "ID": 3,
  "Name": "Kevin",
  "City": "Cilolohan",
  "Address": "Tai’an",
  "Designation": "Paralegal"
}, {
  "ID": 4,
  "Name": "Rebecca",
  "City": "Runović",
  "Address": "Tessaoua",
  "Designation": "Human Resources Manager"
}, {
  "ID": 5,
  "Name": "Nancy",
  "City": "Merritt",
  "Address": "Yur’yevets",
  "Designation": "Assistant Manager"
}, {
  "ID": 6,
  "Name": "Anne",
  "City": "Pio Duran",
  "Address": "Kuala Lumpur",
  "Designation": "Sales Representative"
}, {
  "ID": 7,
  "Name": "Scott",
  "City": "Xiamao",
  "Address": "Banjarmasin",
  "Designation": "Computer Systems Analyst II"
}, {
  "ID": 8,
  "Name": "Howard",
  "City": "Rzeczenica",
  "Address": "Nanyo",
  "Designation": "Recruiting Manager"
}, {
  "ID": 9,
  "Name": "Frances",
  "City": "Tubuhue",
  "Address": "Rambatan",
  "Designation": "Senior Quality Engineer"
}, {
  "ID": 10,
  "Name": "Bruce",
  "City": "Gandi",
  "Address": "Manuel Roxas",
  "Designation": "Senior Financial Analyst"
}, {
  "ID": 11,
  "Name": "Victor",
  "City": "Liuhou",
  "Address": "Sambirejo",
  "Designation": "Actuary"
}, {
  "ID": 12,
  "Name": "Phillip",
  "City": "Fubei",
  "Address": "Ulset",
  "Designation": "Account Representative II"
}, {
  "ID": 13,
  "Name": "Cheryl",
  "City": "Chasŏng",
  "Address": "Otok",
  "Designation": "Mechanical Systems Engineer"
}, {
  "ID": 14,
  "Name": "Arthur",
  "City": "Shimodate",
  "Address": "Morada Nova",
  "Designation": "Payment Adjustment Coordinator"
}, {
  "ID": 15,
  "Name": "Jean",
  "City": "Mojo",
  "Address": "Pushkino",
  "Designation": "Budget/Accounting Analyst II"
}, {
  "ID": 16,
  "Name": "Russell",
  "City": "Qīrah",
  "Address": "Vista Hermosa",
  "Designation": "Research Assistant III"
}, {
  "ID": 17,
  "Name": "Larry",
  "City": "Garoua Boulaï",
  "Address": "Guanchi",
  "Designation": "Office Assistant I"
}, {
  "ID": 18,
  "Name": "Kathleen",
  "City": "Thongwa",
  "Address": "Awilega",
  "Designation": "Social Worker"
}, {
  "ID": 19,
  "Name": "Michael",
  "City": "Hongqi",
  "Address": "Karatau",
  "Designation": "Electrical Engineer"
}, {
  "ID": 20,
  "Name": "Anna",
  "City": "Xiacang",
  "Address": "K Bang",
  "Designation": "Product Engineer"
}];

function populateTable(object) {

    var obj = object;
    var table = $("<table />");
    table[0].border = "1";
    var columns = Object.keys(obj[0]);
    var columnCount = columns.length;
    var row = $(table[0].insertRow(-1));
    for (var i = 0; i < columnCount; i++) {
        var headerCell = $("<th />");
        headerCell.html([columns[i]]);
        row.append(headerCell);
    }

    for (var i = 0; i < obj.length; i++) {
        row = $(table[0].insertRow(-1));
        for (var j = 0; j < columnCount; j++) {
            var cell = $("<td />");
            cell.html(obj[i][columns[j]]);
            row.append(cell);
        }
    }
    
    var dvTable = $("#dvCSV");
    dvTable.html("");
    dvTable.append(table);

}

populateTable(mockData)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dvCSV">
</div>