怎么使用ajax为 datatables 获取数据
1个回答
展开全部
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/html; charset=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 = 0; k < 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 = 0; k < 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}
首先,需要下载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/html; charset=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 = 0; k < 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 = 0; k < 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}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询