如何将JSON数据数组加载到表中?

时间:2017-03-13 01:22:03

标签: javascript jquery json

我对使用jQuery将数据加载到表中感到困惑。如何正确地将数据加载到表中?下面的示例表只使用for循环用JavaScript编写。我不熟悉使用jQuery的$ .each()。

JSON数组数据:这是COLUMN:

{
    "data": [
        [
            "ID",
            "TYPE",
            "TOTAL",
            "1 bed room",
            "2 bed room"
        ]
    ]
}

JSON数组数据:这是DATA:

{
    "data": [
        [
            "100",
            "Total Transaction Amount",
            "9812355000",
            "23397000",
            "13976000"
        ],
        [
            "100",
            "No. of units",
            "1268",
            "3",
            "2"
        ],
        [
            "100",
            "(Total sq.ft.)",
            "",
            "",
            ""
        ],
        [
            "100",
            "Avg. price",
            "7738450",
            "7799000",
            "6988000"
        ],
        [
            "100",
            "Avg. sq.ft.",
            "",
            "",
            ""
        ],
        [
            "100",
            "Max. price",
            "25494000",
            "9918000",
            "7318000"
        ],
        [
            "100",
            "Max. sq.ft",
            "",
            "",
            ""
        ],
        [
            "100",
            "Min. price",
            "5904000",
            "6465000",
            "6658000"
        ],
        [
            "100",
            "Min. sq.ft",
            "",
            "",
            ""
        ]
    ]
}

jQuery脚本:

<script>
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "@Url.Action("FlatType", "Home", new {id = ViewBag.Id})",
                async: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                cache: false,
                success: function (data) {
                    var table = "<tr>";
                    $.each(data.data, function (index, value) {
                        table += "<td>" + value + "</td>";
                        console.log(value);
                    });
                    table += "</tr>";

                    $("#myColumns").html(table);
                }
            });
        });
    </script>

    <script>
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "@Url.Action("FlatTypeById", "Home", new {id = ViewBag.Id })",
                async: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                cache: false,
                success: function (data) {
                    var table = "<tr>";
                    $.each(data.data, function (index, value) {
                        table += "<td>" + value + "</td>";
                        console.log(value);
                    });
                    table += "</tr>";

                    $("#myData").html(table);
                }
            });
        });
    </script>

表:

<table class="table table-bordered">
        <thead id="myColumns"></thead>
        <tbody id="myData"></tbody>
    </table>

示例图片:

See this sample image

3 个答案:

答案 0 :(得分:0)

我编写了一个函数 parse ,它可以帮助您开始学习如何编写处理这些类型数组的函数:

function parse(data) {
    table = "<table>";

    for (var i = 0, len = data.length; i < len; i++) {
        table += "<tr>";
        for (j = 0, len2 = data[i].length; j < len2; j++) {
            table += "<td>" + data[i][j] +  "</td>";
        }
        table += "</tr>";
    }

    table += "</table>";

    return table;
}
$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: "@Url.Action("FlatType", "Home", new {id = ViewBag.Id})",
        async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {

            $("#tableContainer").html(parse(data.data));
        }
    });

OR 您可以使用jQuery版本的代码:

function parse(array) {
    $table = $("<table>");

    $(array).each(function (index, value) {
        $tr = $("<tr>");
        $(value).each(function (index, value) {
            $tr.append($("<td>").html(value));
        });
        $table.append($tr);
    });

    return $table;
}
$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: "@Url.Action("FlatType", "Home", new {id = ViewBag.Id})",
        async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {

            $("#tableContainer").html(parse(data.data));
        }
    });

答案 1 :(得分:0)

首先,您不需要使用jQuery.each,其次,不需要遍历标题对象,因为它只包含一个子数组。

标题部分的代码:

success: function (data) {
    // generate the header row
    var row = "<tr><td>" + data.data[0].join("</td><td>") + "</td></tr>";

    // override the current header row
    $("#myColumns").html(row);
}

身体部位代码:

success: function (data) {
    var $body = $("#myData");         // the body element
    $body.empty();                    // empty it

    data.data.forEach(function(sub) { // for each sub-array sub
        // generate the row
        var row = "<tr><td>" + data.data[0].join("</td><td>") + "</td></tr>";
        $body.append(row);            // append it to the body
    });
}

join连接数组的元素,并返回与作为参数传递的字符串连接的元素的字符串:

&#13;
&#13;
var arr = ["hello", "nice", "world"];
var str = arr.join("*m*");
console.log(str);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

$.Each,类似于for(或更常见的forEach),是一种循环机制,使每个循环机制遍历数组的每个元素。您可以使用任何有意义的循环结构(forwhilereduceforEachmap) - 为您的数据{{{ 1}}或$.each很有意义。

想法

对于您的数据,您将为每个阵列创建一个新的表格行(例如forEach)。对于该数组的每个值(元素),您将创建表标题或表数据元素(例如,<tr><th>)。

另一个例子

使用ES6&{39} <td>forEach,这是另一种创建标题和数据行的方式,而不是您的AJAX调用:

&#13;
&#13;
map
&#13;
// setup JSON objects
let [column, data] = getJSON();

// Create Table Headers
let $thead = $('#myColumns'),
    $tr = $('<tr>');
column.data[0].forEach(col => {
  $tr.append($('<th>').html(col));
});
$thead.append( $tr );

// Create Table Rows
let $tbody = $('#myData');
data.data.forEach(row => {
  let $tr = $('<tr>');
  $tr.append(row.map(val => {
    return $('<td>').html(val);
  }));
  $tbody.append($tr);
});

function getJSON() {
  let column = {
      "data": [
        [
          "ID",
          "TYPE",
          "TOTAL",
          "1 bed room",
          "2 bed room"
        ]
      ]
    },
    data = {
      "data": [
        [
          "100",
          "Total Transaction Amount",
          "9812355000",
          "23397000",
          "13976000"
        ],
        [
          "100",
          "No. of units",
          "1268",
          "3",
          "2"
        ],
        [
          "100",
          "(Total sq.ft.)",
          "",
          "",
          ""
        ],
        [
          "100",
          "Avg. price",
          "7738450",
          "7799000",
          "6988000"
        ],
        [
          "100",
          "Avg. sq.ft.",
          "",
          "",
          ""
        ],
        [
          "100",
          "Max. price",
          "25494000",
          "9918000",
          "7318000"
        ],
        [
          "100",
          "Max. sq.ft",
          "",
          "",
          ""
        ],
        [
          "100",
          "Min. price",
          "5904000",
          "6465000",
          "6658000"
        ],
        [
          "100",
          "Min. sq.ft",
          "",
          "",
          ""
        ]
      ]
    };
  return [column, data];
}
&#13;
&#13;
&#13;

AJAX

如果您想要包含AJAX,那么相同的示例(不调整原始内容)可能如下所示:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered">
  <thead id="myColumns"></thead>
  <tbody id="myData"></tbody>
</table>
&#13;
&#13;
&#13;