我正试图从MongoDB服务器获取表单数据,并使用nodeJs将其显示到数据表中。我已成功使用npm Paginate v-2插件完成了服务器端分页。但是现在搜索不起作用。以下是我的NodeJ和javascript文件代码。请帮助我进行搜索。
NodeJs代码
app.get('/gettable',(req,res)=>{
console.log(req.query);
user.paginate({},{
page:Math.ceil(req.query.start / req.query.length) + 1,
limit:parseInt(req.query.length)
},function(err,result){
var mytable = {
draw:req.query.draw,
recordsTotal:0,
recordsFiltered:0,
data:[],
}
if(err) {
console.log(err);
res.json(mytable);
} else {
if(result.totalDocs > 0) {
mytable.recordsTotal = result.totalDocs;
mytable.recordsFiltered = result.totalDocs;
for(var key in result.docs) {
mytable.data.push([
result.docs[key]['name'],
result.docs[key]['lastname'],
result.docs[key]['email'],
result.docs[key]['pass'],
result.docs[key]['birthdate'],
result.docs[key]['zipcode'],
result.docs[key]['phonenumber'],
]);
}
}
res.json(mytable);
}
});
DisplayTable.Js代码
$(document).ready(function(){
$('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": "http://localhost:8080/gettable"
});
})
正如我所说,我已经成功地从服务器获取数据并通过服务器端分页显示到数据表中,但是搜索无法正常工作,但是在搜索div时无论我搜索什么,我都会在搜索数组中获得该值,就像这样< / p>
search: { value: 'svs', regex: 'false' },
_: '1548653540009' }
但是它没有在数据表中实现以过滤列。
答案 0 :(得分:1)
正如我在comment中所说的那样,当在DataTable中启用服务器端时,搜索将无法立即使用,这是因为现在必须对整个功能(无论是排序,分页,限制还是搜索)进行操作在服务器中实现。 DataTable将仅发送执行该功能所需的参数。以下是仅供参考的代码,未经测试,可能还会出错。您可能会从以下代码获得输入。如果出现错误,请随时编辑以下代码,以帮助将来的读者。
app.get('/gettable',(req,res)=>{
console.log(req.query);
var query = {},
// array of columns that you want to show in table
columns = ['name', 'lastname', 'email', 'pass', 'birthdate', 'zipcode', 'phonenumber',];
// check if global search is enabled and it's value is defined
if (typeof req.query.search !== 'undefined' && req.query.search.value != '') {
// get global search value
var text = req.query.search.value;
// iterate over each field definition to check whether search is enabled
// for that particular column or not. You can set search enable/disable
// in datatable initialization.
for (var i=0; i<req.query.columns.length; i++) {
requestColumn = req.query.columns[i];
column = columns[requestColumn.data];
// if search is enabled for that particular field then create query
if (requestColumn.searchable == 'true') {
query[column] = {
$regex: text,
};
}
}
}
user.paginate(query,{
page:Math.ceil(req.query.start / req.query.length) + 1,
limit:parseInt(req.query.length)
},function(err,result){
var mytable = {
draw:req.query.draw,
recordsTotal:0,
recordsFiltered:0,
data:[],
}
if(err) {
console.log(err);
res.json(mytable);
} else {
if(result.totalDocs > 0) {
mytable.recordsTotal = result.totalDocs;
mytable.recordsFiltered = result.totalDocs;
for(var key in result.docs) {
var data = [];
for(var column in columns) {
data.push(result.docs[key][column]);
}
mytable.data.push(data);
}
}
res.json(mytable);
}
});