将自定义参数传递到datatables.js
问题描述:
我正在使用DataTables将数据加载到表中 - 数据量很大,因此我使用的服务器端处理效果很好。但是,我不确定如何将自定义参数传递给我的ajax调用。将自定义参数传递到datatables.js
如何做到这一点和多个参数(即不同的参数按钮)?
这里是我的代码,迄今:
<script>
$.fn.dataTable.ext.buttons.reload = {
text: 'Reload',
action: function (e, dt, node, config) {
dt.ajax.reload();
}
};
$(document).ready(function() {
$('#landing_pages').DataTable({
dom: 'Blfrtip',
keys: true,
deferRender: true,
responsive: true,
"searching": false,
"lengthMenu": [[10, 25, 50, 500], [10, 25, 50, 500]],
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print', 'reload'
],
"processing": true,
"serverSide": true,
"ajax":{'url': "/data-source/landing-pages/{{profile_id}}{{page_dim}}", "data": function (d) {
d.myKey = "myValue";
// d.custom = $('#myInput').val();
// etc
}}
});
});
</script>
这是从这个例子基于: https://datatables.net/examples/server_side/custom_vars.html
答
一种方法是摧毁数据表,然后用你想要的参数重新初始化。类似这样的:
$.fn.dataTable.ext.buttons.reload = {
text: 'Reload',
action: function (e, dt, node, config) {
// Get the profile_id and page_dim values to pass in to the initializer
// Destroy the datatable
$("#MyTable").dataTable().fnDestroy();
// reinitialize the datatable with the new call with the variables
InitializeTable(profile_id, page_dim);
}
};
function InitializeTable(profile_id, page_dim) {
var initTable = {
dom: 'Blfrtip',
keys: true,
deferRender: true,
responsive: true,
"searching": false,
"lengthMenu": [[10, 25, 50, 500], [10, 25, 50, 500]],
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print', 'reload'
],
"processing": true,
"serverSide": true,
"ajax":{'url': "/data-source/landing-pages/" + profile_id + "/" + page_dim, "data": function (d) {
d.myKey = "myValue";
};
// Initialize the data table with the parameters above
$("#MyTable").dataTable(initTable);
}
感谢您的帮助。那么我如何为多个人做这个? – Adders
多重是什么?表?对于表格,为每个要初始化的表格创建一个函数,每个表格都带有自己的ajax调用和参数 – Simon
没有参数,对不起,如果我遗漏了一些明显的东西。我希望能够通过动态参数 – Adders