我想解释奥马尔的答案,并希望这对其他人特别是初学者有益。
如果您将数据从服务器发送到 DataTable 并期望它会根据您在 Datatable 声明中定义的设置自动对您的记录进行分页,那么您错了。您必须在服务器端编写分页功能。每当您单击 Datatable 的“NEXT”按钮时,它将调用服务器代码(Web 服务、方法等)并发送一个参数列表,您可以使用这些参数列表非常轻松地实现分页。
请仔细阅读本文,您可以很容易地在您使用的任何技术中实现这一点。
以下是使用 DataTable 正确实现分页所需遵循的步骤。
真的很简单很容易,只要注意。
我正在使用 DataTable、Spring MVC、Spring REST 和 Hibernate。
JavaScript 代码
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
<script src= "https://code.jquery.com/jquery-1.12.4.js"></script>
<script src= "https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"paging":true,
"ajax": "rest/getQuestions",
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "city" },
{ "data": "country" },
{ "data": "date" },
{ "data": "email" },
{ "data": "subject" },
{ "data": "question" },
{ "data": "status" },
{ "data": "views" },
{ "data": "submittedBy" }
]
} );
} );
</script>
</head>
rest/getQuestions 是 WebService 调用。我的表的名称是 Question_tbl,我正在显示我的表的所有列。
HTML 表格
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> City </th>
<th> Country </th>
<th> Date </th>
<th> Email </th>
<th> Subject </th>
<th> Question </th>
<th> Status </th>
<th> Views </th>
<th> Submitted By </th>
</tr>
</thead>
</table>
Spring 休息服务
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RequestParam;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
@RequestMapping(value = "/rest/getQuestions", method = RequestMethod.GET)
public String getPaginatedQuestions(@RequestParam Integer draw, @RequestParam Integer start, @RequestParam Integer length ) {
List<Question_tbl> paginatedQuestions = questionService.getPaginatedQuestionsSrv(start, length);
int questionCount = questionService.getQuestionCountByLimit(300);
QuestionDataTable dt = new QuestionDataTable();
dt.setDraw(draw);
dt.setRecordsTotal(questionCount);
dt.setRecordsFiltered(questionCount);
dt.setData(paginatedQuestions);
ObjectMapper mapper = new ObjectMapper();
try {
String jsonGenerated = mapper.writeValueAsString(dt);
return jsonGenerated;
} catch (JsonProcessingException ex) {
Logger.getLogger(QuestionRestController.class.getName()).log(Level.SEVERE, null, ex);
}
return new JsonMappingException("Exception").toString();
}
Question_tbl 是我的实体表,它映射到数据库表名称Question。 3个请求参数draw、start、length从Datatable发送到服务器。
还有其他参数,我在下面展示了,但这些足以实现分页。将它们发送到服务层以获取分页记录。在数据库层,你只需要简单地实现下面的代码,你就会得到需要的记录。
DAO 方法
public List<Question_tbl> getPaginatedQuestionsDao(int start, int length){
Query qry = sessionFactory.getCurrentSession().createQuery("from Question_tbl q ORDER BY q.date DESC");
qry.setFirstResult(start);
qry.setMaxResults(length);
return qry.list();
}
什么是QuestionDataTable及其用途
要获取 Json 格式的数据,我们有一个 RestService。调用 RestService 时,从服务调用返回的结果 json 不是 DataTable 所需的格式。所以我们需要处理返回的 JSON 以正确显示 DataTable 中的数据。返回的实际 JSON 是这样的
{
"id": 10,
"name": "Muhammad.s",
"city": "Lahore",
"country": "Pakistan",
"date": 1491549259000,
"email": "emil@email.com",
"subject": "Testing Subject",
"question": "Test Question-1",
"status": "unanswered",
"views": 0,
"submittedBy": null
},
{
"id": 8,
"name": "Tariq.s",
"city": "Hyderabad",
"country": "Pakistan",
"date": 1490465223000,
"email": "abc@gmail.com",
"subject": "Subject 2",
"question": "Test question",
"status": "unanswered",
"views": 0,
"submittedBy": null
}
但 DataTable 所需的格式应该有 3 个初始元素,分别是 "draw"、"recordsTotal"、"recordsFiltered"。有关 JSON 格式的进一步说明,请查看此 link。这是所需且正确的格式。
{
"draw": 9,
"recordsTotal": 12,
"recordsFiltered": 12,
"data": [
{
"id": 12,
"name": "Qalb-E-Muhammadi",
"city": "Oval",
"country": "England",
"date": 1491550466000,
"email": "email@gmail.com",
"subject": "Test Subject 1",
"question": "Test Question",
"status": "unanswered",
"views": 0,
"submittedBy": null
},
{
"id": 11,
"name": "Buzjani",
"city": "Sydney",
"country": "Australia",
"date": 1491549438000,
"email": "email@email.com",
"subject": "Testing Subject",
"question": "Testing Question",
"status": "unanswered",
"views": 0,
"submittedBy": null
}
]
}
为此,我创建了名为 “QuestionDataTable” 的实用程序类。
public class QuestionDataTable {
private int draw;
private int recordsTotal;
private int recordsFiltered;
private List<Question_tbl> data;
// Getters, Setters
}
然后我通过上面定义的 Rest 服务中定义的 ObjectMapper 类将 QuestionDataTable 对象转换为 Json。
从DataTable返回给Web Service的请求参数
draw:1
columns[0][data]:firstName
columns[0][name]:
columns[0][searchable]:true
columns[0][orderable]:true
columns[0][search][value]:
columns[0][search][regex]:false
columns[1][data]:lastName
columns[1][name]:
columns[1][searchable]:true
columns[1][orderable]:true
columns[1][search][value]:
columns[1][search][regex]:false
columns[2][data]:age
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
您可以在调用 Rest Service 后在浏览器中查看请求的 HEAD 部分中发送的上述参数。图片为chrome示例Chrome example
我知道这是一篇很长的帖子,我已尽力涵盖所有相关方面,这样您就不必在这里跳来跳去。我希望这将节省您寻找相关解决方案的宝贵时间。