目標(biāo):
使用 jQuery Datatable 構(gòu)造數(shù)據(jù)列表,并且增加或者隱藏相應(yīng)的列,已達(dá)到數(shù)據(jù)顯示要求。同時(shí), jQuery Datatable 強(qiáng)大的功能支持:排序,分頁,搜索等。
Query Datatable 能良好支持?jǐn)?shù)據(jù)完全加載到本地后構(gòu)建數(shù)據(jù)列表,排序、分頁、搜索等功能就會(huì)自帶,不需要我們?nèi)リP(guān)心,在此主要說明通過后臺(tái)動(dòng)態(tài)的加載數(shù)據(jù),已達(dá)到在大數(shù)據(jù)面前提高效率的效果。
1.? 通過后臺(tái)進(jìn)行分頁
2.? 通過后臺(tái)進(jìn)行排序
3.? 通過后臺(tái)進(jìn)行搜索
具體使用方法:
1. 首先構(gòu)建我們需要的數(shù)據(jù)列表,以及頁面顯示表格。
1 2 3 4 5 6 7 8 9 10 <table?id="datatable"?width="100%"?border="1"> ????<thead> ????????<tr> ????????????<th>ID</th> ????????????<th>First Name</th> ????????????<th>Last Name</th> ????????????<th>Operation</th> ????????</tr> ????<thead> </table>
表格建立很簡單,只需用將表格定義好id ,以及表頭定義好。
2.? 我們可以到 jQuery Datatable 官網(wǎng)上去下載一份 jQuery 和 jQuery Datatable 的js 庫。 https://datatables.net/examples/server_side/simple.html 。
3.? 然后將這兩個(gè)文件引入到頁面文件中,注意 jQuery 的庫一定要在最前面,因?yàn)轫撁婕虞d的有順序,保證后面的擴(kuò)展庫能使用到jQuery 。同時(shí),請(qǐng)下載最新的 jQuery Datatable 版本,因?yàn)樗膶懛ㄒ约皡?shù)更加簡潔,功能更加多。【注:參數(shù)區(qū)別會(huì)在附錄寫明】
4.? 編寫前端代碼。我們是要使用Ajax 對(duì)后臺(tái)進(jìn)行請(qǐng)求,因此在配置 datatable 時(shí),加上 { "serverSide" : true } ,已保證頁面在加載時(shí)就請(qǐng)求后臺(tái),以及每次對(duì)datatable 進(jìn)行操作時(shí)也是請(qǐng)求后臺(tái)。【附:如果想加上一點(diǎn)加載效果,可以增加 { "processing" :? true } 】。
配置請(qǐng)求后臺(tái)URL : { "ajax" :? "load" }
5.? 配置數(shù)據(jù)返回對(duì)應(yīng)具體的列。在Datatable 中,屬性 columns 用來配置具體列的屬性,包括對(duì)應(yīng)的數(shù)據(jù)列名,是否支持搜索,是否顯示,是否支持排序等。根據(jù)上述頁面配置我們具體的列。如下:
1 2 3 4 5 6 7 8 9 10 11 12 $(document).ready(function() { ????????$("#datatable").dataTable({ ????????????"processing":?true, ????????????"serverSide":?true, ????????????"ajax"?:?"load", ????????????"columns": [ ????????????????{"data":?"id",?"bSortable":?false}, ????????????????{"data":?"firstName"}, ????????????????{"data":?"lastName"} ????????????] ????????}); ????});
第一列ID ,設(shè)置為不允許排序。也可以增加不顯示: { "visible" :? false }
6.? 此時(shí)對(duì)于后臺(tái)而言,返回的數(shù)據(jù)一定要按照一定規(guī)范。如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 { ????"draw": 2, ????"recordsTotal": 11, ????"recordsFiltered": 11, ????"data": [ ????????{ ????????????"id": 1, ????????????"firstName":?"Troy", ????????????"lastName":?"Young" ????????}, ????????{ ????????????"id": 2, ????????????"firstName":?"Alice", ????????????"lastName":?"LL" ????????}, ????????{ ????????????"id": 3, ????????????"firstName":?"Larry", ????????????"lastName":?"Bird" ????????} ????????// ...... ????] }
參數(shù)解釋:
draw: 表示請(qǐng)求次數(shù)
recordsTotal: 總記錄數(shù)
recordsFiltered: 過濾后的總記錄數(shù)
data: 具體的數(shù)據(jù)對(duì)象數(shù)組
7.? 最后一列Operation ,我們沒有任何數(shù)據(jù),用來放我們的通用操作列,如修改鏈接。? Datatable 提供了自定義列 columnDef s屬性,他的值為數(shù)組對(duì)象,具體代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 $(document).ready(function() { ????????$("#datatable").dataTable({ ????????????"processing":?true, ????????????"serverSide":?true, ????????????"ajax"?:?"load", ????????????"columns": [ ????????????????{"data":?"id",?"bSortable":?false}, ????????????????{"data":?"firstName"}, ????????????????{"data":?"lastName"} ????????????], ????????????"columnDefs": [ ????????????????{ ????????????????????"targets": [3], ????????????????????"data":?"id", ????????????????????"render":?function(data, type, full) { ????????????????????????return?"<a href='/update?id="?+ data +?"'>Update</a>"; ????????????????????} ????????????????} ????????????] ????????}); ????});
targets : 表示具體需要操作的目標(biāo)列,下標(biāo)從0 開始
data: ?表示我們需要的某一列數(shù)據(jù)對(duì)應(yīng)的屬性名
render: 返回需要顯示的內(nèi)容。在此我們可以修改列中樣式,增加具體內(nèi)容
? 屬性列表: data , 之前屬性定義中對(duì)應(yīng)的屬性值
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? t ype ,? 未知
? ??full , ?? ?全部數(shù)據(jù)值可以通過屬性列名獲取
具體效果圖如下:
8.? 我們?cè)賮砜淳唧w如何進(jìn)行搜索、排序、分頁。由于只是為了做demo ,因此使用最簡單的 JDBC+Servlet 的方式來實(shí)現(xiàn)。
首先我們來看,datatable 給我們?cè)谧稣?qǐng)求是傳遞過來的參數(shù):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 =============== Request Paramerters ================ draw:?1 columns[0][data]: id columns[0][name]: columns[0][searchable]:?true columns[0][orderable]:?true columns[0][search][value]: columns[0][search][regex]:?false columns[1][data]: firstName columns[1][name]: columns[1][searchable]:?true columns[1][orderable]:?true columns[1][search][value]: columns[1][search][regex]:?false columns[2][data]: lastName columns[2][name]: columns[2][searchable]:?true columns[2][orderable]:?true columns[2][search][value]: columns[2][search][regex]:?false order[0][column]:?0 order[0][dir]: asc start:?0 length:?10 search[value]: search[regex]:?false _:?1399345292266 =============== Request Paramerters ================
其中有用的數(shù)據(jù)就是 start, length, order[0][column], order[0][dir], search[value] 。具體參數(shù)意思:
start:? 其實(shí)記錄位置
length: 頁面顯示數(shù)量
order[0][column]:? 因?yàn)槭嵌S的表格,因此只有一維需要排序,所以order 的下標(biāo)未 0.? 該屬性表示第幾列需要排序。
order[0][dir]:? 排序方式 ASC | DESC
search[value]: ?search 輸入框中的值
9.? 這幾個(gè)屬性對(duì)后臺(tái)進(jìn)行排序、搜索、分頁很有用。【注:因?yàn)槭嵌S表,并且只是對(duì)一列進(jìn)行操作,自然就是一維的,所以order 下標(biāo)始終為 1 。以后操作二維表有待研究。】
首先來看包含這幾個(gè)功能的DAO 層代碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 /** ?????* This method includes the search, sort, pagination ?????* @param pageSize ?????* @param startRecord ?????* @param sortColumn ?????* @param sortDir ?????* @param searchValue ?????* @return ?????*/ ????public?List<Data> loadDataList(int?pageSize,?int?startRecord, String sortColumn, String sortDir, String searchValue) { ????????List<Data> results =?new?ArrayList<Data>(); ????????StringBuffer sql =?new?StringBuffer("select * from data "); ?????????????????????????????? ????????// for search ????????String[] columnsName = {?"id",?"firstName",?"lastName"?}; ????????boolean?searchAble =?false; ????????if(searchValue !=?null?&& !"".equals(searchValue)) { ????????????sql.append("where "); ????????????searchAble =?true; ????????} ?????????????????????????????? ????????if(searchAble) { ????????????StringBuffer temp =?new?StringBuffer(); ????????????for?(String column : columnsName) { ????????????????temp.append( column+?" like '%"?+ searchValue +?"%' or "); ????????????} ????????????sql.append(temp.substring(0, temp.length() -?3)); ????????} ?????????????????????????????? ????????// for order ????????sql.append(" order by "?+ sortColumn +?" "?+ sortDir +?" "); ?????????????????????????????? ????????// for pagination ????????sql.append(" limit ?,? "); ????????System.out.println(sql.toString()); ?????????????????????????????? ????????try?{ ????????????stmt = conn.prepareStatement(sql.toString()); ????????????stmt.setInt(1, startRecord); ????????????stmt.setInt(2, startRecord + pageSize); ?????????????????????????????????? ????????????ResultSet rs = stmt.executeQuery(); ????????????while(rs.next()) { ????????????????Data data =?new?Data(); ????????????????data.setId(rs.getInt(1)); ????????????????data.setFirstName(rs.getString(2)); ????????????????data.setLastName(rs.getString(3)); ?????????????????????????????????????? ????????????????results.add(data); ????????????} ?????????????????????????????????? ????????}?catch?(SQLException e) { ????????????// TODO Auto-generated catch block ????????????e.printStackTrace(); ????????} ?????????????????????????????? ????????return?results; ????}
DAO層中,統(tǒng)計(jì)代碼類似,只用把分頁和排序的 SQL 拼接去掉即可。
我們需要將我們的數(shù)據(jù)轉(zhuǎn)換成JSON 返回給前端,并且還要顯示總記錄數(shù),過濾后總記錄數(shù)。因此我們需要一個(gè)統(tǒng)一的類來將這些數(shù)據(jù)進(jìn)行封裝。由于在一個(gè)系統(tǒng)中不只一個(gè)對(duì)象需要展示到前端,因此統(tǒng)一的做一個(gè)為 datatable 封裝類。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 package?com.web.vo; import?java.util.List; /** ?* This VO used to generate the JSON data for data table, so please ensure that the attribute name is correct. ?* If you want to define the fields name by yourself, please visit: https://datatables.net ?* @author troyyang ?* ?* @param <T> ?*/ public?class?DataVO<T> { ????private?int?draw;?// Client request times ????private?int?recordsTotal;?// Total records number without conditions ????private?int?recordsFiltered;?// Total records number with conditions ????private?List<T> data;?// The data we should display on the page ????// getter and setter method }
萬事具備,只欠前后交互代碼。此處使用最簡單的 servlet 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 // For pagination ????????int?pageSize =?10; ????????int?startRecord =?0; ????????String size = request.getParameter("length"); ????????if?(!"".equals(size) && size !=?null) { ????????????pageSize = Integer.parseInt(size); ????????} ????????String currentRecord = request.getParameter("start"); ????????if?(!"".equals(currentRecord) && currentRecord !=?null) { ????????????startRecord = Integer.parseInt(currentRecord); ????????} ????????// For sortable ????????String sortOrder = request.getParameter("order[0][column]"); ????????String sortDir = request.getParameter("order[0][dir]"); ????????System.out.println("sortOrder: "?+ sortOrder); ????????System.out.println("sortDir: "?+ sortDir); ?????????????????????? ????????// For search ????????String searchValue = request.getParameter("search[value]"); ????????int?count =?0; ????????List<Data> results =?new?ArrayList<Data>(); ????????count = dao.count(); ????????results = dao.loadDataList(pageSize, startRecord, columnsName[Integer.parseInt(sortOrder)], sortDir, searchValue); ????????DataVO<Data> result =?new?DataVO<Data>(); ????????result.setDraw(Integer.parseInt(request.getParameter("draw") ==?null???"0" ????????????????: request.getParameter("draw")) +?1); ????????result.setData(results); ????????result.setRecordsTotal(count); ????????result.setRecordsFiltered(count); ????????Gson gson =?new?Gson(); ????????String output = gson.toJson(result); ????????System.out.println("Output JSON: \n"?+ output); ????????PrintWriter out = response.getWriter(); ????????out.write(output); ????????out.flush(); ????????out.close();
附錄:
使用 jQuery Datatable 1.10之前的版本,必須使用 sAjaxSource 進(jìn)行請(qǐng)求,但是請(qǐng)求數(shù)據(jù)和現(xiàn)在版本的請(qǐng)求數(shù)據(jù)不同,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 =============== Request Paramerters ================ sEcho:?1 iColumns:?4 sColumns: ,,, iDisplayStart:?0 iDisplayLength:?10 mDataProp_0: id sSearch_0: bRegex_0:?false bSearchable_0:?true bSortable_0:?false mDataProp_1: firstName sSearch_1: bRegex_1:?false bSearchable_1:?true bSortable_1:?true mDataProp_2: lastName sSearch_2: bRegex_2:?false bSearchable_2:?true bSortable_2:?true mDataProp_3: id sSearch_3: bRegex_3:?false bSearchable_3:?true bSortable_3:?true sSearch: bRegex:?false iSortCol_0:?0 sSortDir_0: asc iSortingCols:?1 _:?1399515247114 =============== Request Paramerters ================
更過特性,持續(xù)更新......
本文出自 “SG-YYZ” 博客,請(qǐng)務(wù)必保留此出處http://sgyyz.blog.51cto.com/5069360/1408251
《新程序員》:云原生和全面數(shù)字化實(shí)踐 50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀
總結(jié)
以上是生活随笔 為你收集整理的jQuery Datatable 实用简单实例 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。