如何将动态json加载到jquery数据表

时间:2015-07-06 15:22:25

标签: javascript jquery json jquery-plugins datatables

我想将动态数据加载到我的jquery数据表中。这意味着,在我从服务器获取json数据之前,我不知道它包含哪些字段,但我确定json是有效的。它将如下所示,

"data": [
{
  "first_name": "Airi",
  "last_name": "Satou",
  "position": "Accountant",
  "office": "Tokyo",
  "start_date": "28th Nov 08",
  "salary": "$162,700"
},
{
  "first_name": "Angelica",
  "last_name": "Ramos",
  "position": "Chief Executive Officer (CEO)",
  "office": "London",
  "start_date": "9th Oct 09",
  "salary": "$1,200,000"
}

有时,它可能只包含'first_name'和'last_name'。

我搜索了很长时间,所有样本都指定了'aoColumnsDef'或'aoColumns'。但我不知道确切的文件。有没有办法使用json中的字段名称作为表的标题和字段值作为表的主体来填充jquery数据表?例如,json数据只包含两个字段'first_name'和'last_name',该表应包含两列'first_name'和'last_name'。如果json包含3个字段,则表应显示3列。我确信“数据”中的所有项目都有相同的字段。

提前致谢!

2 个答案:

答案 0 :(得分:7)

使用您的示例数据,将第一条记录作为“示例”数据循环,然后动态创建列定义,如下所示:

编辑:使用xhr调用来检索数据的原始代码示例

$(document).ready(function() {
  
  //callback function that configures and initializes DataTables
  function renderTable(xhrdata) {
    var cols = [];

    var exampleRecord = xhrdata[0];

    var keys = Object.keys(exampleRecord);

    keys.forEach(function(k) {
      cols.push({
        title: k,
        data: k
          //optionally do some type detection here for render function
      });
    });

    var table = $('#example').DataTable({
      columns: cols
    });

    table.rows.add(xhrdata).draw();
  }

  //xhr call to retrieve data
  var xhrcall = $.ajax('/path/to/data');

  //promise syntax to render after xhr completes
  xhrcall.done(renderTable);
});

var data = [{
  "first_name": "Airi",
  "last_name": "Satou",
  "position": "Accountant",
  "office": "Tokyo",
  "start_date": "28th Nov 08",
  "salary": "$162,700"
},
{
  "first_name": "Angelica",
  "last_name": "Ramos",
  "position": "Chief Executive Officer (CEO)",
  "office": "London",
  "start_date": "9th Oct 09",
  "salary": "$1,200,000"
}];

$(document).ready( function () {
  var cols = [];
  
  var exampleRecord = data[0];
  
  //get keys in object. This will only work if your statement remains true that all objects have identical keys
  var keys = Object.keys(exampleRecord);
  
  //for each key, add a column definition
  keys.forEach(function(k) {
    cols.push({
      title: k,
      data: k
      //optionally do some type detection here for render function
    });
  });
  
  //initialize DataTables
  var table = $('#example').DataTable({
    columns: cols
  });
  
  //add data and draw
  table.rows.add(data).draw();
});
body {
  font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
  margin: 0;
  padding: 0;
  color: #333;
  background-color: #fff;
}


div.container {
  min-width: 980px;
  margin: 0 auto;
}
<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>

    <link href="//datatables.net/download/build/nightly/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script>

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>
  </head>
  <body>
    <div class="container">
      <table id="example" class="display" width="100%">
      </table>
    </div>
  </body>
</html>

答案 1 :(得分:0)

如何首先从收到的JSON构建一个简单的html表,并且仅在使用创建的表构建DataTable之后。

var table = $("#tableId");
table.append('<thead>....</thead>');
table.append('<tbody>....</tbody>');

table.DataTable();