简体   繁体   English

将json数据添加到数据表

[英]Add json data to datatables

I am trying to populate datatables with a complex json scheme, however I don't know exactly how to do it. 我正在尝试使用复杂的json方案填充数据表,但是我不知道该怎么做。

  • First, some parts of json are nested and it needs iteration. 首先,json的某些部分是嵌套的,需要迭代。
  • Second I need to create some markup, basically a href link. 其次,我需要创建一些标记,基本上是href链接。

Here is what I have: 这是我所拥有的:

$(document).ready(function(){
   $('#empTable').DataTable({
      'processing': true,
      'serverSide': true,
      'serverMethod': 'post',

      'ajax': {
          'url':'/dashboard/ajaxgetrequests',
          dataSrc: "json_list"
      },
      'columns': [
         { data: 'firstname' },
         { data: 'funding_project_name' } // this must be a link like <a href='/<relation_id>'><funding_project_name></a>
      ]
   });
});

{  
   "json_list":{  
      "125":{  
         "firstname":"John",
         "funding_project_name":"A",
         "relation_id": "7"

      },
      "133":{  
         "firstname":"Cesar",
         "funding_project_name":[  
            "A",
            "B"
         ],
         "relation_id":[  
            "7",
            "9"
         ]
      }
   }
}

1) For nested JSON you can use something like this: 1)对于嵌套的JSON,您可以使用以下代码:

// JSON structure for each row:
//   {
//      "engine": {value},
//      "browser": {value},
//      "platform": {
//         "inner": {value}
//      },
//      "details": [
//         {value}, {value}
//      ]
//   }
$('#example').dataTable( {
  "ajaxSource": "sources/deep.txt",
  "columns": [
    { "data": "engine" },
    { "data": "browser" },
    { "data": "platform.inner" },
    { "data": "details.0" },
    { "data": "details.1" }
  ]
} );

2) To edit and insert a link you can use columns.render ( documentation ) 2)要编辑和插入链接,可以使用columns.render文档

$('#example').dataTable( {
  "columnDefs": [ {
    "targets": 0,
    "data": "download_link",
    "render": function ( data, type, row, meta ) {
      return '<a href="'+data+'">Download</a>';
    }
  } ]
} );

Honestly, there may be a better built in way of handling this but when I experience things that do not fit the exact mold of using the base datatable functionality, I prefer to take manual control of the generation. 老实说,可能有更好的内置方法来处理此问题,但是当我遇到与使用基本数据表功能不完全相符的事物时,我更喜欢手动控制生成。 This will give you an overview on how to do it with your structure: 这将为您概述如何使用您的结构:

Just basic html for your table (nothing really to see here): 只是表格的基本html(在这里什么也看不到):

<table id="empTable">
<thead>
  <tr><th>First Name</th><th>ProjectName</th></tr>
</thead>
<tbody></tbody>
</table>

In JS we declare a variable we can use throughout our script then on ready event we instatiate our datatable: 在JS中,我们声明一个变量,我们可以在整个脚本中使用它,然后在ready事件中,我们使数据表无效:

var dt;

$(document).ready(function () {
  dt = $('#empTable').DataTable();
  loadDT();
});

We will also use a function call 'loadDT()' and what this will do is trigger a ajax call to the backend to get your json, in this example, I'm just gonna mock it but in your world so this on the ajax success: 我们还将使用函数调用“ loadDT()”,此操作将触发对后端的ajax调用以获取您的json,在本示例中,我只是模拟了它,但在您的世界中,因此在ajax上进行了模拟成功:

Iterate your list and determine the types then use the api call row.add to dynamically add new rows to your table. 遍历列表并确定类型,然后使用api调用row.add将新行动态添加到表中。 (notice we are reusing the stored variable dt that we initially declared.) This is where you can do whatever custom logic fun you need to do. (注意,我们正在重用最初声明的存储变量dt。)在这里,您可以执行所需的任何自定义逻辑操作。

function loadDT(){
  var mockJSON = { "json_list":{  "125":{  "firstname":"John","funding_project_name":"A","relation_id": "7"},"133":{  "firstname":"Cesar","funding_project_name":["A","B"],"relation_id":["7","9"]}}};

  $.each(mockJSON.json_list, function (i, n){
    if(Array.isArray(n.funding_project_name)) {
      $.each(n.funding_project_name, function (i2, p){
        dt.row.add([n.firstname,'<a href="/'+ n.relation_id[i2] +'">' + p + '</a>']);
        dt.draw(false);
      });
    } else {
      dt.row.add([n.firstname,  '<a href="/"' + n.relation_id + '"">' + n.funding_project_name + '</a>']);
      dt.draw(false);
    }
  });
}

Like previously stated, there may be some built in functions to handle this that I am unaware but when things get complicated, just know you can take manual control of it. 如前所述,可能有一些内置函数可以解决我不知道的问题,但是当事情变得复杂时,只要知道您可以对其进行手动控制即可。

Full Example: 完整示例:

 var dt; $(document).ready(function () { dt = $('#empTable').DataTable(); loadDT(); }); function loadDT(){ var mockJSON = { "json_list":{ "125":{ "firstname":"John","funding_project_name":"A","relation_id": "7"},"133":{ "firstname":"Cesar","funding_project_name":["A","B"],"relation_id":["7","9"]}}}; $.each(mockJSON.json_list, function (i, n){ var projLinks = ""; if(Array.isArray(n.funding_project_name)) { $.each(n.funding_project_name, function (i2, p){ projLinks += '<a href="/'+ n.relation_id[i2] +'">' + p + '</a> '; }); } else { projLinks = '<a href="/"' + n.relation_id + '"">' + n.funding_project_name + '</a>'; } dt.row.add([n.firstname, projLinks]); dt.draw(false); }); } 
 <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <table id="empTable"> <thead> <tr><th>First Name</th><th>ProjectName</th></tr> </thead> <tbody></tbody> </table> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM