尝试使用jQuery将JSON文件转换为HTML表

时间:2017-08-08 10:49:44

标签: javascript jquery html json

我正在尝试使用jQuery将Array转换为HTML表。但是,浏览器不会显示JSON文件。请参阅下面的代码。

JSON文件

[
{
    "Book ID": "1",
    "Book Name": "Computer Architecture",
    "Category": "Computers",
    "Price": "125.60"
},
{
    "Book ID": "2",
    "Book Name": "Asp.Net 4 Blue Book",
    "Category": "Programming",
    "Price": "56.00"
},
{
    "Book ID": "3",
    "Book Name": "Popular Science",
    "Category": "Science",
    "Price": "210.40"
}

HTML和JS

<script>
$(document).ready(function () {
    $.getJSON("result.json", function (data) {

        var arrItems = [];      // THE ARRAY TO STORE JSON ITEMS.
        $.each(data, function (index, value) {
            arrItems.push(value);       // PUSH THE VALUES INSIDE THE ARRAY.
        });

        // EXTRACT VALUE FOR TABLE HEADER.
        var col = [];
        for (var i = 0; i < arrItems.length; i++) {
            for (var key in arrItems[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // CREATE DYNAMIC TABLE.
        var table = document.createElement("table");

        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

        var tr = table.insertRow(-1);                   // TABLE ROW.

        for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");      // TABLE HEADER.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }

        // ADD JSON DATA TO THE TABLE AS ROWS.
        for (var i = 0; i < arrItems.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = arrItems[i][col[j]];
            }
        }

        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("showData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    });
});

嗨gusy,我正在尝试使用jQuery将Array转换为HTML表。但是,浏览器不会显示JSON文件。请参阅下面的代码。

0 个答案:

没有答案