【问题标题】:How to load JSON data array into table?如何将 JSON 数据数组加载到表中?
【发布时间】:2017-03-13 01:22:02
【问题描述】:

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

JSON 数组数据:这是 COLUMN:

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

JSON 数组数据:这是数据:

{
    "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

【问题讨论】:

  • 为什么有两个请求?只需发出一个请求,并将索引 0 处的子数组用作表头,其余的用作表的主体(必须调整服务器端代码)!
  • 或者更好的data 会像:{header: [...], body: [[...], [...], ...]}!
  • @ibrahimmahrir 实际上有 2 个查询我们用于其他目的先生。
  • @imprezzeb 用于其他目的先生。
  • @imprezzeb 有效!

标签: javascript jquery json


【解决方案1】:

首先你不需要使用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 连接数组的元素并返回一个字符串,该字符串与作为参数传递的字符串连接:

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

【讨论】:

    【解决方案2】:

    我写了一个函数,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));
            }
        });
    

    您可以使用 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));
            }
        });
    

    【讨论】:

    • 感谢您的帮助,先生,我喜欢它!但我使用了 $.ajax({ })。 ajax怎么做?
    • 如果您愿意,我可以编写一个严重依赖 jQuery 的版本,但是当您在我的帖子底部添加代码时,您是否遇到错误?如果有,是什么?
    • JSON.parse 将抛出错误,因为数据已经是一个对象(由于使用了dataType: "json")。阅读更多关于jQuery.ajax!
    • 您应该将返回的表格插入表格容器中。喜欢
    【解决方案3】:

    $.Each,类似于for(或更常见的forEach),是一种循环机制,它使每个循环遍历数组的每个元素。您可以使用任何有意义的循环构造(forwhilereduceforEachmap)——对于您的数据,$.eachforEach 很有意义.

    想法

    对于您的数据,您将为每个数组创建一个新的表格行(例如,&lt;tr&gt;)。对于该数组的每个值(元素),您将创建一个表头或表数据元素(例如,&lt;th&gt;&lt;td&gt;)。

    另一个例子

    从您的 AJAX 调用中抽象出来,这是另一种创建标题和数据行的方法,使用 ES6 的 forEachmap

    // 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];
    }
    <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>

    AJAX

    如果您想包含 AJAX,则相同的示例(无需调整大部分原始内容)可能类似于:

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

    【讨论】:

    • 谢谢先生,您的回答是正确的,但我无法理解。可以使用include ajax()吗?
    • @PaulGeorge 包括
    • 先生,如何处理 null 如果 null 然后 0 零然后输出删除标题或列标题。
    • 不完全确定你在问什么。如果您不想在没有值的情况下创建标题单元格,则可以在标题部分的 $tr.append( 行上方插入 if (col === null) return;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多