【问题标题】:How to load a jQuery.DataTables grid with dynamic JSON data如何使用动态 JSON 数据加载 jQuery.DataTables 网格
【发布时间】:2023-04-05 07:05:03
【问题描述】:

我正在尝试将一些简单的 JSON 数据加载到 jQuery.DataTables (datatables.net) 中,网格按照 HTML 中的定义显示,但不会根据新数据而更改。

我错过了什么?有什么建议吗?

HTML:

<table id="example" class="display" style="width:100%;">
<thead>
    <tr>
        <th>Id</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>0</td>
    </tr>
</tbody>

JavaScript:(已加载 jQuery 和 jQuery.DataTables)

$(document).ready(function () {
    $("#example").DataTable({
        data: [{ Id: "1" }, { Id: "2" }],
        columns: { data: "Id", title: "ID" }
    });
});

【问题讨论】:

    标签: javascript jquery json datatables


    【解决方案1】:

    您的列数据应设置为数组。像这样的

    $(document).ready(function () {
        $("#example").DataTable({
            data: [{ Id: "1" }, { Id: "2" }],
            columns: [{ data: "Id", title: "ID" }]
        });
    });
    

    对于使用 ajax 的动态数据

    $(document).ready(function() {
        $('#example').DataTable( {
            "ajax": "data/objects.txt",
            "columns": [
                { "data": "name" },
                { "data": "position" },
                { "data": "office" },
                { "data": "extn" },
                { "data": "start_date" },
                { "data": "salary" }
            ]
        } );
    } );
    

    JSON txt 文件

    {
      "data": [
        {
          "id": "1",
          "name": "Tiger Nixon",
          "position": "System Architect",
          "salary": "$320,800",
          "start_date": "2011/04/25",
          "office": "Edinburgh",
          "extn": "5421"
        },
        {
          "id": "2",
          "name": "Garrett Winters",
          "position": "Accountant",
          "salary": "$170,750",
          "start_date": "2011/07/25",
          "office": "Tokyo",
          "extn": "8422"
        }
      ]
    }
    

    更多详情Here

    【讨论】:

      【解决方案2】:

      试试这个

        var options = {
              data: [{ Id: "1" }, { Id: "2" }],
              columns: { data: "Id", title: "ID" }
          }
         var dataTable =  $("#example").DataTable(options );
      
         // Reload and refresh
         dataTable.draw(); 
      

      【讨论】:

        【解决方案3】:

        所以,我用于注入 JSON 数据(或作为变量)的代码很好,问题是我忘记在该网格初始化之前添加的网格的另一个单击事件(坏坏我)

        $("#example " + "tbody").on("click", "tr", function () {
        var data = table.row(this).data();
        isDebug && console.log('You clicked on ' + data[0] + '\'s row');
        isDebug && console.log(data);
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-28
          • 2015-09-23
          相关资源
          最近更新 更多