我目前正在使用DataTables的服务器端选项,我当前的问题是数据表中的页码仅显示1。这里进一步解释一下我的代码:
Javascript:
var oTable1 = $('#users-table').dataTable({
"bDestroy": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/v1/users",
"bPaginate": true,
"aoColumns": [
{ "mData": "id" },
{ "mData": "username" },
{ "mData": "name" },
{ "mData": "acctype" },
{ "mData": "country" },
{ "mData": "createdAt" },
{ "mData": "button" }
]
});
/v1/用户:
viewAll: function(req, res, next) {
var colS = "";
switch(req.query.iSortCol_0){
case '0': colS = 'id'; break;
case '1': colS = 'username'; break;
case '2': colS = 'firstname'; break;
case '3': colS = 'acctype'; break;
case '4': colS = 'country'; break;
case '5': colS = 'createdAt'; break;
default: break;
};
var options = {
sort: colS+' '+req.query.sSortDir_0,
or: [
{ acctype: { 'contains': req.query.sSearch }},
{ id: { 'contains': req.query.sSearch }},
{ username: { 'contains': req.query.sSearch }},
{ lastname: { 'contains': req.query.sSearch }},
{ firstname: { 'contains': req.query.sSearch }},
{ country: { 'contains': req.query.sSearch }},
{ createdAt: { 'contains': req.query.sSearch }}
],
limit: req.query.iDisplayLength
};
console.log(req.query);
console.log(req.query.sSearch);
//console.log(options);
var p = req.query.iDisplayStart+1;
//console.log(req.query.iDisplayStart);
Users.find(options).paginate({ page: p, limit: req.query.iDisplayLength }).exec(function(err, usr){
if(err){
res.send(500, { error: 'DB error' });
} else {
var retuser = [];
usr.forEach(function(user){
retuser.push({ id: user.id, username: user.username, name: user.firstname+" "+user.lastname, acctype: user.acctype, country: user.country, createdAt: user.createdAt, button: "<a class='blue' href='#view-user' data-toggle='modal' id='user-info'> <i class='icon-zoom-in bigger-130'></i></a>" });
});
Users.count().exec(function(err, result){
var json = {
aaData: retuser,
iTotalRecords: result,
iTotalDisplayRecords: usr.length
};
res.contentType('application/json');
res.json(json);
});
}
});
},
基本上发生的事情是: 当我更改页面时
.paginate({ page: p, limit: req.query.iDisplayLength })
改为2,则显示第2页应显示的内容,如果将其更改为1,则显示第1页应显示的内容。并且当更改要显示的记录数时,显示第11条记录。所以我想我如何从 Controller 检索数据没有问题。
我以为 DataTables 会根据 iTotalDisplayRecords
和 iTotalRecords
自动添加页码,但事实证明并非如此。我的代码是否有问题,或者我认为有什么问题,我必须在数据表中添加页码?
最佳答案
我认为问题是您在 iTotalDisplayRecords
中返回了错误的值:
"iTotalRecords": 11,
"iTotalDisplayRecords": 10
来自manual :
int
iTotalRecords
Total records, before filtering (i.e. the total number of records in the database)int
iTotalDisplayRecords
Total records, after filtering (i.e. the total number of records after filtering has been applied - not just the number of records being returned in this result set)
不执行过滤时,iTotalRecords
应等于 iTotalDisplayRecords
。
要解决此问题,您需要在应用过滤后计算记录总数,并将该值用于 iTotalDisplayRecords
而不是 usr.length
.
关于jquery - Sails 中的服务器端分页与数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30772911/