實際開發過程中可能會遇到這樣的需求,後端計算的列表信息需要展示的頁面上。這個列表信息沒有保存在數據庫就會考慮使用前端分頁組件,並且想使用bootstrap框架的模態框展示該部分數據,當有觸發事件的時候就會彈出模態框展示計算結果列表,datatables支持查詢與分頁等配置。
頁面需要引入css、js
頁面必須引入datatables、bootstrap、jquery相關資源
<link href="https://cdn.bootcss.com/datatables/1.10.16/css/jquery.dataTables.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/datatables/1.10.16/js/jquery.dataTables.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
定義觸發按鈕
這裏觸發函數是按鈕的onclick點擊方法,觸發show()
<button class="btn btn-primary btn-lg" data-toggle="modal" onclick="show()">
開始演示模態框
</button>
定義模態框
模態框分標題和內容區域,需要指定模態框的id方便jquery調用“myModal”
<!-- 模態框(Modal) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">
模態框(Modal)標題
</h4>
</div>
<div class="modal-body">
<!--模態框內容-->
<table class="table table-bordered jambo_table bulk_action table-striped table-hover"
id="example">
<thead>
<tr class="headings">
<th>職工號</th>
<th>姓名</th>
<th>部門</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">關閉
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
定義js
需要在js中定義按鈕的觸發函數show()
需要注意的地方:
1、dataTable每次加載表格之後,如果數據變化需要銷燬之前的重新繪製;(dataTable原理是一次性加載數據,前端處理數據進行分頁)
2、bProcessing配置爲展示正在加載的提示(建議)
3、oLanguage配置中文
4、表格通過ajax加載數據,columns必須按照如下代碼。
//表頭對應的列
//outid、name、dpname分別爲需要展示的數據列,必須保證(表頭【模態框裏】、數據列【如下代碼】、後端實體類三個地方命名一致)
"columns": [
{ "data": "outid" },
{ "data": "name" },
{ "data": "dpname" }
]
function show() {
var url= [[@{/xzl/lnry}]];
//再次查詢時先刪除paymentlist,如果少了以下語句每次只能查詢一次,第二次點擊查詢就不執行。
var table=$('#example').dataTable();
if(table){
table.fnDestroy();
}
$('#example').dataTable( {
"ajax": url,
"bProcessing" : true,
"oLanguage": { //國際化配置
"sProcessing" : "正在獲取數據,請稍後...",
"sLengthMenu" : "顯示 _MENU_ 條",
"sZeroRecords" : "沒有您要搜索的內容",
"sInfo" : "從 _START_ 到 _END_ 條記錄 總記錄數爲 _TOTAL_ 條",
"sInfoEmpty" : "記錄數爲0",
"sInfoFiltered" : "(全部記錄數 _MAX_ 條)",
"sInfoPostFix" : "",
"sSearch" : "搜索",
"sUrl" : "",
"oPaginate": {
"sFirst" : "第一頁",
"sPrevious" : "上一頁",
"sNext" : "下一頁",
"sLast" : "最後一頁"
}
},
"columns": [
{ "data": "outid" },
{ "data": "name" },
{ "data": "dpname" }
]
} );
$('#myModal').modal('show')
}
後端ajax請求的數據接口
重要!數據列表需要封裝在data字段中構成dataTable可解析的json
@GetMapping("lnry")
@ResponseBody
public String dqLnrs() {
//展示的數據列表
List<Xzlio> lnry = xzlioRepository.selectByOutId(ry);
//數據封裝
Map map = new HashMap();
//重要!數據列表需要封裝在data字段中構成dataTable可解析的json
map.put("data", lnry);
//轉化成json格式傳遞至頁面
return JsonUtil.toJson(map);
}
展示效果