<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="http://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css"> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script> <!-- <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>--> <script type="text/javascript" src="http://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script> </head> <body> <button id="rebuild">点击重建</button> <div id="app"> </div> </body> <script> $('#app').html('<table class="display" id="example"></table>');//动态生成表格 $(document).ready(function () { //这里用异步请求后端,获取数据 var dataset = [ {id: 0, name: 'alice', age: 2, money: 1522}, {id: 2, name: 'vilson', age: 5, money: 2454} ];//数据格式 var colunms = [ { "title": '序号', "class": "center", "render": function (data, type, full, meta) { return meta.row + 1; } } ]; //将要渲染的colunms //根据后端返回的数据,取第一条数据,拼装colunms $.each(dataset[0], function (key, val) { var obj = { "title": key, "class": "center", "render": function (data, type, full, meta) { return full[key]; } }; colunms.push(obj); }); var table = $('#example').DataTable({ "pageLength": 1, "processing": true, //是否显示处理状态(排序的时候,数据很多耗费时间长的话,也会显示这个) "data": dataset,//设置数据 "columns": colunms }); $("#rebuild").click(function () { dataset = [ {id: 3, name: 'xxx', age: 21, money: 1522}, {id: 4, name: 'cccc', age: 53, money: 1522} ];//数据格式 table.destroy(); table = $('#example').DataTable({ "processing": true, //是否显示处理状态(排序的时候,数据很多耗费时间长的话,也会显示这个) "pageLength": 2, "data": dataset,//设置数据 "columns": colunms }); }); }); </script> <style> .center { text-align: center; } </style> </html>