【问题标题】:Dynamic datatable with api带 api 的动态数据表
【发布时间】:2019-07-12 13:41:54
【问题描述】:

我有一个数据表,我想使用 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>

【问题讨论】:

  • 您在执行此操作时遇到了什么问题?
  • @Mayank Pandeyz 我无法显示数据。
  • 试试这个:github.com/pandeyz/…

标签: javascript jquery html datatable bootstrap-4


【解决方案1】:

使用 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>

【讨论】:

  • 谢谢,但是数据会改变,所以我们不能复制和粘贴它在url中的json数据。
  • @lakshmipriya我已经更新了我的编码以从 URL 获取数据
  • @lakshmipriya 是的
  • @lakshmipriya 请稍候
猜你喜欢
  • 2019-06-29
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2020-11-19
  • 2017-01-24
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多