te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - how to load dynamic json to jquery datatable - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to load dynamic json to jquery datatable - Stack Overflow

programmeradmin2浏览0评论

I want to load dynamic data into my jquery datatable. That means, before I get the json data from server, I don't know what fields it contains, but I'm sure the json is valid. It will looks like below,

"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"
}

]

sometimes, it may only contains 'first_name' and 'last_name'.

I've searched a long time, all of the samples specify 'aoColumnsDef' or 'aoColumns'. But I don't know the exact fileds. Is there a way to fill jquery datatable using the field name in json as the header of the table and the field value as the body of the table? For example, the json data only contains two fields, 'first_name' and 'last_name', the table should contains two columns 'first_name' and 'last_name'. If the json contains 3 fields, the table should display the 3 columns. I'm sure all of the items in "data" have the same fields.

Thanks in advance!

I want to load dynamic data into my jquery datatable. That means, before I get the json data from server, I don't know what fields it contains, but I'm sure the json is valid. It will looks like below,

"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"
}

]

sometimes, it may only contains 'first_name' and 'last_name'.

I've searched a long time, all of the samples specify 'aoColumnsDef' or 'aoColumns'. But I don't know the exact fileds. Is there a way to fill jquery datatable using the field name in json as the header of the table and the field value as the body of the table? For example, the json data only contains two fields, 'first_name' and 'last_name', the table should contains two columns 'first_name' and 'last_name'. If the json contains 3 fields, the table should display the 3 columns. I'm sure all of the items in "data" have the same fields.

Thanks in advance!

Share Improve this question asked Jul 6, 2015 at 15:22 Allen4TechAllen4Tech 2,1843 gold badges29 silver badges70 bronze badges 2
  • I understand that you don't know what kind of object you are going to receive in the array of data, but all the objects in the array would be equal? – josedefreitasc Commented Jul 6, 2015 at 15:35
  • @josedefreitasc yes! – Allen4Tech Commented Jul 6, 2015 at 15:41
Add a ment  | 

2 Answers 2

Reset to default 9

Using your example data, loop over the first record as your 'example' data, then create the column definitions on the fly like so:

EDIT: example of original code with an xhr call to retrieve data

$(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 pletes
  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./jquery-1.11.1.min.js"></script>

    <link href="//datatables/download/build/nightly/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="//datatables/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>

How about build a simple html table from received JSON first and only after this build DataTable using created table.

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

table.DataTable();
发布评论

评论列表(0)

  1. 暂无评论