jQuery datatables 的ajax数据源

jQuery datatables 的ajax数据源,第1张

Datatables 支持多种格式的数据,在配置中ajax配置项中,使用dataSrc可以指定数据源的来源。数据源需要配合columns属性使用,columns是列显示数组,指定数据项的来源和显示方式。如果dataSrc没有指定,数据源是data,比如下面的数据:

如果数据源是数组,那么数据源需要设置为空,比如下面的数据:

上面这些情况中,columns需要设置为:

如果数据是纯数组:

那么columns定义数组的列编号,如果不定义,按缺省顺序:

需要引入 jquery.dataTables.js 以及相关的css。

创建表及添加删除数据:

dataTables中的为其设置一个数据源,这个数据源可以是一个数组或者是一个对象。

比较常见的方法还是使用ajax异步调用。

添加删除数据主要根据具体情况,在回调函数中进行处理·····

dataTables是一种很好用前端表格显示库。当加载大量数据时,可以用Ajax 获取数据来提高效率,增速网页加载速率。下面以一个例子作示范。

首先,需要下载jquery以及dataTables库。这里使用的是版本是jQuery v1.11.3和DataTables 1.10.9。下载网址:http://datatables.net/。

先上网页的代码。要注意的是,table中的thead和tbody必须要有。

[html] view plaincopy

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<meta http-equiv="Content-Type" content="text/htmlcharset=UTF-8">

<head>

<link href="http://www.zhuhaihengxin.com/libs/datatables/1.10.0/css/jquery.dataTables.css" rel="stylesheet">

<title>dataTable example</title>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript" src="jquery.dataTables.js"></script>

<script type="text/javascript">

$(document).ready(function() {

$("#datatable").dataTable({

"processing" : true,

"serverSide" : true,

"paginationType":"full_numbers",

"ajax" : "load",

"columns" : [

{"data" : "id"},

{"data" : "firstName"},

{"data" : "lastName"}

]

})

})

</script>

<style>

h2{

text-align:center

}

div {

float: left

margin: 10px

padding: 4px

}

a{

margin:5px

}

table,tr,td,th{

border:2px solid #3aec7b

border-collapse:collapse

}

</style>

</head>

<body>

<TABLE id="datatable">

<THEAD>

<tr>

<th>ID</th>

<th>First Name</th>

<th>Last Name</th>

</tr>

</THEAD>

<tbody>

</tbody>

</TABLE>

</body>

</html>

当网页加载的时候,ajax发出请求,如下所示。

[html] view plaincopy

draw=[1]

columns[0][data]=[id]

columns[0][name]=[]

columns[0][searchable]=[true]

columns[0][orderable]=[false]

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]

_=[1441278114568]

其中,draw是请求的序号,start是数据的偏移量,length是需要返回的最大数据条数。search[value]是查找的值。

服务端采用java的servlet完成。为简单起见,这里直接采用继承HttpServlet的方式实现。数据本应该从数据库中提取,但这里为了

简单,生成了静态数据集合作为数据源。每次请求都从集合中查找匹配的数据,然后转换成JSON返回。JSON库采用阿里的fastjson。

代码如下所示。

[java] view plaincopy

package jspTest

import java.io.IOException

import java.util.ArrayList

import java.util.Arrays

import java.util.Enumeration

import java.util.LinkedList

import java.util.Random

import javax.servlet.ServletException

import javax.servlet.annotation.WebServlet

import javax.servlet.http.HttpServlet

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

import com.alibaba.fastjson.JSON

import com.alibaba.fastjson.JSONObject

import java.util.List

import java.util.Map

/**

* Servlet implementation class DataLoad

*/

public class DataLoad extends HttpServlet {

private static final long serialVersionUID = 1L

static class Person {

private long id

private String firstName

private String lastName

public long getId() {

return id

}

public void setId(long id) {

this.id = id

}

public String getFirstName() {

return firstName

}

public void setFirstName(String firstName) {

this.firstName = firstName

}

public String getLastName() {

return lastName

}

public void setLastName(String lastName) {

this.lastName = lastName

}

public boolean match(String pattern) {

return firstName.contains(pattern) || lastName.contains(pattern) || Long.toString(id).contains(pattern)

}

}

private static Random r = new Random()

private static List<Person>ps = new ArrayList<Person>()

static {

int size = 2512

for (int k = 0k <size++k)

ps.add(generatePerson())

}

static Person generatePerson() {

Person p = new Person()

p.setId(ps.size() + 1)

p.setFirstName(generateName())

p.setLastName(generateName())

return p

}

private static String generateName() {

StringBuilder sb = new StringBuilder()

sb.append((char) (r.nextInt(26) + 'A'))

int len = 2 + r.nextInt(4)

for (int k = 0k <len++k)

sb.append((char) (r.nextInt(26) + 'a'))

return sb.toString()

}

private List<Person>result

public List<Person>getResult(){

return result

}

/**

* @see HttpServlet#HttpServlet()

*/

public DataLoad() {

super()

}

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

* response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

int start=0

int length=10

String pattern=""

String draw="1"

Map<String,String[]>params=request.getParameterMap()

for(String attr:params.keySet()){

String[] val=params.get(attr)

System.out.println(attr+"="+Arrays.toString(val))

if(attr.equals("start"))

start=Integer.parseInt(val[0])

if(attr.equals("length"))

length=Integer.parseInt(val[0])

if(attr.equals("search[value]"))

pattern=val[0]

if(attr.equals("draw"))

draw=val[0]

}

int total=filter(start, length, pattern)

JSONObject obj = new JSONObject()

obj.put("draw", draw)

obj.put("recordsTotal", ps.size())

obj.put("recordsFiltered", total)

System.out.println(obj.toJSONString())

obj.put("data", result)

response.getWriter().println(obj.toJSONString())

}

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

* response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response)

}

private int filter(int start,int length,String pattern){

result=new LinkedList<Person>()

int total=0

for(Person s:ps){

if(!s.match(pattern))

continue

++total

if(start-->0)

continue

if(length--<=0)

continue

result.add(s)

}

return total

}

public static void main(String[] rags) {

System.out.println(JSON.toJSONString(ps))

DataLoad load=new DataLoad()

load.filter(0, 10, "")

System.out.println(JSON.toJSONString(load.getResult()))

load.filter(0, 10, "a")

System.out.println(JSON.toJSONString(load.getResult()))

load.filter(10, 10, "a")

System.out.println(JSON.toJSONString(load.getResult()))

load.filter(20, 10, "a")

System.out.println(JSON.toJSONString(load.getResult()))

}

}

服务端返回的JSON数据如下所示。其中draw是请求中的draw参数,data是表格中的数据。recordsFiltered是过滤后的数据总数,recordsTotal是原始数据总数。

[html] view plaincopy

{"recordsFiltered":2512,

"data":[{"firstName":"Bzf","id":1,"lastName":"Hazkm"},{"firstName":"Imxi","id":2,"lastName":"Oieb"},{"firstName":"Glyag","id":3,"lastName":"Gvqlf"},{"firstName":"Lwbhl","id":4,"lastName":"Fvvf"},{"firstName":"Audds","id":5,"lastName":"Seunp"},{"firstName":"Otbrq","id":6,"lastName":"Hnal"},{"firstName":"Loji","id":7,"lastName":"Qicn"},{"firstName":"Rjy","id":8,"lastName":"Emrygr"},{"firstName":"Gcglkd","id":9,"lastName":"Ldgrs"},{"firstName":"Txh","id":10,"lastName":"Qwe"}],

"draw":"1",

"recordsTotal":2512}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11892543.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存