简体   繁体   中英

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.

  • First, some parts of json are nested and it needs iteration.
  • Second I need to create some markup, basically a href link.

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:

// 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 )

$('#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):

<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:

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:

Iterate your list and determine the types then use the api call row.add to dynamically add new rows to your table. (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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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