带有API的动态数据表

时间:2019-02-19 05:56:29

标签: javascript jquery html datatable bootstrap-4

我有一个数据表,我想使用API​​动态显示数据。如何做到这一点,我的API是这个url,并且正在使用bootstrap4 datattable。这是我的fiddle。谁能建议我该怎么做?提前致谢。

$(document).ready(function(){
    $('#example').DataTable( {
        ajax:           "https://api.myjson.com/bins/un18a",
        deferRender:    true,
        scrollY:        200,
        scrollCollapse: true,
        scroller:       true,
        initComplete: function () 
        {
            this.api().row( 1000 ).scrollTo();
        }
    });
});
<table class="table table-bordered" id="example" width="100%" cellspacing="0">
    <thead>
       <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Subject</th>
          <th>Message</th>
          <th>Details</th>
       </tr>
    </thead>
    <tbody>
    </tbody>
 </table>

1 个答案:

答案 0 :(得分:2)

带有API的动态数据表

$.getJSON( "https://api.myjson.com/bins/un18a", function( data ) {
   //console.log(data);
   jsonArr =data;
   //header
  if(jsonArr.length >0)
  {
    let firstRow =jsonArr[1];
    let allKeys =Object.keys(firstRow);
    var tblHeader = document.getElementById("header");
    allKeys.forEach(function(key) {
      var newel = document.createElement('th');
      newel.innerHTML = key;
      tblHeader.appendChild(newel);
  });

  var tblBody = document.getElementById("tbody");

  //rows
  jsonArr.forEach(function(row) {
     var newTr = document.createElement('tr');
     allKeys.forEach(function(key) {
        var newel = document.createElement('td');
        newel.innerHTML = row[key];
        newTr.appendChild(newel);
     });
    tblBody.appendChild(newTr); 
  });  
  }

  $('#example').DataTable();

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/dt-1.10.18/datatables.min.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

 
<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/dt-1.10.18/datatables.min.js"></script>


<table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr id="header">
            </tr>
        </thead>
        <tbody id="tbody">
        </tbody>
    </table>