我正在使用Datatables在Web应用程序中显示表格数据,并已配置它使用服务器端处理,即通过AJAX查询过滤后的数据。 我想根据我的应用程序特定的其他参数进行筛选,即对应于一些用户选项(例如通过界面中的复选框)。 如何让DataTables将这些额外的筛选参数传递给服务器?
我正在使用Datatables在Web应用程序中显示表格数据,并已配置它使用服务器端处理,即通过AJAX查询过滤后的数据。 我想根据我的应用程序特定的其他参数进行筛选,即对应于一些用户选项(例如通过界面中的复选框)。 如何让DataTables将这些额外的筛选参数传递给服务器?
此答案已更新至1.10.6版本
现在可以使用ajax选项来完成此操作。
示例代码
$table.dataTable({
"ajax": {
"url": "example.com/GetData",
"type": "POST",
"data": function(d) {
d.Foo = "bar";
d.Bar = "foo";
d.FooBar = "foobarz";
}
},
"serverSide":true,
});
将Foo,Bar和FooBar作为表单数据与其他现有参数(例如draw、start、length等)一起作为附加参数发布,因此根据您的服务器端语言,您可以相应地读取它们。
在实际场景中,您可能会有一个搜索按钮和一些输入,您可以通过调用来触发过滤过程
var table = $table.DataTable();
table.ajax.reload();
当按钮被点击时。
解决方案是使用DataTables的fnServerParams选项,它允许您添加自定义参数以在发送到服务器的XMLHttpRequest中发送。例如:
$(document).ready(function() {
$('#example').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/IndexXhr",
"fnServerParams": function (aoData) {
var includeUsuallyIgnored = $("#include-checkbox").is(":checked");
aoData.push({name: "includeUsuallyIgnored", value: includeUsuallyIgnored});
}
});
});
$('#id').change( function() { oTable.fnDraw(); } );
其中oTable是一个包含您的数据表格对象的变量 oTable = $('#itemsTable').dataTable({....})
- Jerzy Gebler花了几个小时终于做到了!
我将把完整的方法发布在这里,以帮助大家。
需要使用 fnServerParams
选项,该选项允许添加自定义参数以发送到服务器的XMLHttpRequest中。例如:
以下是我使用的coffescript代码:
jQuery ->
table = $('#logs').dataTable
bProcessing: true
bServerSide: true
sAjaxSource: $('#logs').data('source')
fnServerParams: (aoData) ->
applicationName = $("#applicationName").val()
aoData.push
name: "applicationName"
value: applicationName
return
$("#applicationName").on "change", ->
table.fnDraw()
return
我的HTML文件包含具有ID applicationName
的输入元素。请注意,我使用了fnDraw()
元素,以便在输入值更改时启用重绘请求。
fnDraw()
功能。如果没有这个功能,这个方法对我来说似乎没有什么用处。 - Peeyusht = $("#tbl_SearchCustomer").DataTable({
processing: true,
serverSide: true,
info: true,
ajax: {
url: '../Data/SearchCustomer',
data: function (data) {
data.CustomerCategoryID = $("#CustomerCategoryID").val(); // dynamic parameter
delete data.columns;
}
},
deferRender: true,
columns: [
{ "data": "FullName" },
],
dom: 'lfrtip'
});
这对我有用
$(document).ready(function() {
table = $('#okmorders').DataTable( {
// "ajax": 'http://cdpaha2.dev/admin/organizations/okm_orders'
serverSide: true,
"paging": true,
"searching": false ,
// "info": false,
"bLengthChange": false,
// "iDisplayLength":50,
// "aaSorting": [],
// "oLanguage": { "sEmptyTable": "No orders present " } ,
"aoColumnDefs" : [
{ 'bSortable' : false, 'aTargets' : [ 6 ]}
],
// "fnServerParams": function (aoData) {
// aoData.push({name: "includeUsuallyIgnored"});
// },
ajax: {
url: 'yoururl.json' ,
type: 'POST',
data:
{
'startDate':function(){return $("#startDate").val(); },
'endDate': function(){return $("#endDate").val(); } ,
'placedBy':function(){return $("#placedBy").val(); },
'customer_po': function(){return $("#customer_po").val(); } ,
'customer_ref': function(){return $("#customer_ref").val(); }
}
},
} );