页面代码:
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/plugins/datatables/dataTables.bootstrap.css">
<script src="/static/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="/static/plugins/datatables/dataTables.bootstrap.min.js"></script>
<div class="box-body">
<table id="example2" class="table table-bordered table-hover">
<thead>
<tr role="row">
<th>列1</th>
<th>列2</th>
<th>列3</th>
<th>列4</th>
<th>列5</th>
<th>列6</th>
</tr>
</thead>
<tbody class="tdoby_student_data">
</tbody>
<tfoot>
</tfoot>
</table>
</div>
</div>
Datatable代码
<script>
var table;
$(function () {
//提示信息
$.fn.dataTable.ext.errMode = 'none';
var lang = {
"sProcessing": "处理中...",
"sLengthMenu": "每页 _MENU_ 项",
"sZeroRecords": "没有匹配结果",
"sInfo": "当前显示第 _START_ 至 _END_ 项,共 _TOTAL_ 项。",
"sInfoEmpty": "当前显示第 0 至 0 项,共 0 项",
"sInfoFiltered": "(由 _MAX_ 项结果过滤)",
"sInfoPostFix": "",
"sSearch": "搜索:",
"sUrl": "",
"sEmptyTable": "表中数据为空",
"sLoadingRecords": "载入中...",
"sInfoThousands": ",",
"oPaginate": {
"sFirst": "首页",
"sPrevious": "上页",
"sNext": "下页",
"sLast": "末页",
"sJump": "跳转"
},
"oAria": {
"sSortAscending": ": 以升序排列此列",
"sSortDescending": ": 以降序排列此列"
}
};
//初始化表格
table = $("#example2").dataTable({
language: lang, //提示信息
autoWidth: false, //禁用自动调整列宽
stripeClasses: ["odd", "even"], //为奇偶行加上样式,兼容不支持CSS伪类的场合
processing: true, //隐藏加载提示,自行处理
serverSide: false, //启用服务器端分页
searching: false, //禁用原生搜索
orderMulti: false, //启用多列排序
order: [], //取消默认排序查询,否则复选框一列会出现小箭头
renderer: "bootstrap", //渲染样式:Bootstrap和jquery-ui
pagingType: "simple_numbers", //分页样式:simple,simple_numbers,full,full_numbers
columnDefs: [{
"targets": 'nosort', //列的样式名
"orderable": false //包含上样式名‘nosort'的禁止排序
}],
// 主要是这一块实现分页展示后端返回的数据
ajax: function (data, callback, settings) {
console.log(data);
//ajax请求数据
$.ajax({
type: "GET",
url: "${base}/user/getAll",
cache: false, //禁用缓存
data: {}, //传入组装的参数
dataType: "json",
success: function (result) {// result可以造点假数据测试
var returnData = {};
returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
//返回数据全部记录
returnData.recordsTotal = result.length;
//后台不实现过滤功能,每次查询均视作全部结果
returnData.recordsFiltered = result.length;
//data: {draw: 2, order: Array(1), start: 0, length: 20, search: {…}, …}
// start 首行展示数据(会根据分页自动改变),length每页展示多少行
//当前页展示的数据列表(将数据截取展示)
returnData.data = result.slice(data.start,data.start+data.length);
//此时的数据需确保正确无误,异常判断应在执行此回调前自行处理完毕
callback(returnData);
}
});
},
"columns": [
//跟你要显示的字段是一一对应的。我这里只显示八列
{'data': 'username'},
{'data': 'realName'},
{'data': 'sex'},
{'data': 'age'},
{'data': 'address'},
{'data': 'grade'},
{'data': 'headImage'},
{
"data": "谨慎操作",
render: function (data, type, full) {
//可对数据进行处理,再显示
}
},
],
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) { //列样式处理
}
})
.api();
//此处需调用api()方法,否则返回的是JQuery对象而不是DataTables的API对象
});
</script>