禁用初始自动 ajax 调用 - DataTable 服务器端分页
Disable initial automatic ajax call - DataTable server side paging
我有一个用服务器端分页初始化的数据表,它工作正常。此 table 触发 ajax,在初始化期间拉取数据并呈现到 table 上。但是我最初需要空 table 并使用 load() 或 reload() 单击按钮加载 table 数据,例如:
myTable.api().ajax.reload();
这是我的 table 初始化:
function initTestTable(){
myTable = $('#testTable').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "testTableData.html",
"type": "GET",
},
"columns": [
{ "data": "code" },
{ "data": "description" }
]
});
}
初始化的时候应该有办法限制table的加载吧?我阅读了文档但找不到。请提出建议。
您可以使用 deferLoading 参数并将其设置为 0
。这将延迟数据加载,直到过滤器、排序操作或 draw/reload Ajax 以编程方式发生。
function initTestTable(){
myTable = $('#testTable').dataTable({
"processing": true,
"serverSide": true,
"deferLoading": 0, // here
"ajax": {
"url": "testTableData.html",
"type": "GET",
},
"columns": [
{ "data": "code" },
{ "data": "description" }
]
});
}
要在单击按钮时触发 Ajax,您可以在处理程序中添加类似以下内容的内容:
function buttonClickHandler(event){
$('#testTable').DataTable().draw();
}
请参见下面的示例进行演示。
$(document).ready(function() {
// AJAX emulation for demonstration only
$.mockjax({
url: '/test/0',
responseTime: 200,
response: function(settings){
this.responseText = {
draw: settings.data.draw,
data: [
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ]
],
recordsTotal: 1000,
recordsFiltered: 1000
};
}
});
$('#example').DataTable({
"processing": true,
"serverSide": true,
"deferLoading": 0,
"ajax": {
"url": "/test/0",
"type": "GET"
}
});
$('#btn-reload').on('click', function(){
$('#example').DataTable().draw()
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link href="//cdn.datatables.net/1.10.5/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script>
<script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>
</head>
<body>
<p>
<button id="btn-reload">Reload</button>
</p>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</body>
</html>
我可以通过传递一个带有 URL 的额外参数来识别事件来解决此问题。
例如,对于加载,我使用 action="load"
作为查询参数初始化数据 table,对于搜索等其他操作,我传递 action="search"
。有了这个,我在后端将能够识别呼叫来源。如果它不是 "load"
,我将提取数据并传递(就像现在的实现一样)。否则(如果 "load")那么我将传递空数据,这将向我显示 "No Data Found"
消息,就好像它没有进行 ajax 调用一样。
这是我的代码 - Table 初始化:
function initTestTable(){
myTable = $('#testTable').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "testTableData.html?action=load",
"type": "GET",
},
"columns": [
{ "data": "code" },
{ "data": "description" }
]
});
}
对于加载以外的事件(例如按钮单击):
var newUrl = 'testTableData.html?action=search';
myTable.api().ajax.url(newUrl).load();
这是我必须在不修改 table init 的情况下进行的,这会导致错误。
感谢@JSelser 和@davidkonrad 的所有建议:)
这就是我最初在页面加载时加载空数据表的方式。然后我使用 eventListener 通过 ajax 加载数据。我找不到任何我只是玩弄它的文档,它就像一个魅力。
ref 文件 - dataTables.js, table-advanced.js
$(document).ready(function(){
option = "I";
// pick a table list or something
$("#dropdownList").on("change", function(){
option = $('option:selected:not(:disabled)',this).val();
if($.fn.DataTable.isDataTable('#table_001')){
$('#table_001').dataTable().fnDestroy();
InitDataTable(option);
}
else{
InitDataTable("disabled");
}
});
//add/delete/update a row maybe?
$("#signupForm #add_btn").on("click",function(e){
if($("#signupForm").valid()){
var oTable1 = $('#table_001').DataTable(); ///load .ajax structure
//Successful Submit!
oTable1.ajax.reload();
$("#note").html(<img src="/images/loading.gif" alt="loading">');
}
});
//On draw occurs everytime you call table.ajax.reload();
$('#table_001').on( 'draw.dt', function () {
if(option !== "I")
var evtname = $('select[name="EVENT"] option:selected:not(:disabled)').text();
if(evtname !== undefined)
$("#event_name").html("The " + evtname + " Signup Sheet").addClass("xs-small");
// keep track of values for table input fields on each draw
$("[aria-controls='table_001'][type='search']").attr('hth_orig',$(" [aria-controls='table_001'][type='search']").val());
//Don't initialize on draw
TableAdvanced.init('table_001','N');
});
var InitDataTable = function(choice){
var oTable1 = $('#table_001').dataTable( {
"processing": true,
"serverSide": true,
"lengthMenu": [10,25,50,100], // records pulldown
"iDisplayLength": 25, // # records to initially display
"ajax": {
"url": "http://www.domain.com",
"data": function (d) { // pass additional
d.user = user;
d.choice = choice;
d.cols = "15"; // TOTAL <td> tags per <tr> tag
},
// Load attendee total and pending total sections
complete: function (d) {
recordstotal = d.responseJSON.recordsTotal;
attendeetotal = d.responseJSON.attendeeTotal;
//console.log(JSON.stringify(d.responseJSON.data));
if ( attendeetotal == '0') {
$("#totalAttendees").html("No one has signed up for this event yet");
}
else {
$("#totalAttendees").html("Event Total: " + attendeetotal + " attendees");
}
$("#add-atn").removeClass("hidden");
}
},
// insert code to execute after table has been redrawn
"fnDrawCallback": function( oSettings ) {
// Column filtering
var table = $('#table_001').DataTable();
$("#table_001 tfoot th").each( function ( i ) { // i = 0,1...
if($.trim($(this).html()) != '') {
save_html = $(this).html();
$(this).empty();
var select = $(save_html)
.appendTo( this )
.on( 'change', function () {
table.column( i, { filter: 'applied' }).search($(this).val()).draw();
});
$("#table_001 tfoot th:eq("+i+") input").val(save_value);
}
});
//console.log($("#table_001 tfoot th").length);
},
"columns": [// set "data" to next sequential number in double quotes
{"data":"0",// Set "name" to field name that will be refd
"name": "skip"},
{"data":"1",
"name": "skip"},
{"data": "2",
"name": "skip"},
{"data":"3",
"name": "lname"},
{"data":"4",
"name": "fname"}
{"data":"5",
"name": "skip"}
],
"columnDefs": [
// what columns should be hidden?
{
"targets": [1], // what element starting with 0
"class":"hidden" // class to attach to <td>
},
// what columns should NOT be sortable?
{
"targets": [0,1,2,5,6,7,8,9,12,13,14],
"sortable": false, // sortable?
},
// what columns should NOT be searchable?
{
"targets": [0,1,2,6,7,8,9,12,13,14],
"searchable": false, // searchable?
}
],
"createdRow": function( row, data, dataIndex ) {
//manipulate the specific column in the row
//$(row).addClass( 'form-group' );
// $('td', row).eq(2).addClass('form-group'); // Added to <td>
},
// Specify initial sort order
"order": [[ '10', "desc" ],[ '11', "desc" ],['3',"asc"],['4',"asc"]]
});
// handle 1st page table load initialization using
TableAdvanced.init('table_001','Y');
});
}
注意:您可以添加一些逻辑来选择默认选项(如果有可用且未禁用的选项)。
我有一个用服务器端分页初始化的数据表,它工作正常。此 table 触发 ajax,在初始化期间拉取数据并呈现到 table 上。但是我最初需要空 table 并使用 load() 或 reload() 单击按钮加载 table 数据,例如:
myTable.api().ajax.reload();
这是我的 table 初始化:
function initTestTable(){
myTable = $('#testTable').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "testTableData.html",
"type": "GET",
},
"columns": [
{ "data": "code" },
{ "data": "description" }
]
});
}
初始化的时候应该有办法限制table的加载吧?我阅读了文档但找不到。请提出建议。
您可以使用 deferLoading 参数并将其设置为 0
。这将延迟数据加载,直到过滤器、排序操作或 draw/reload Ajax 以编程方式发生。
function initTestTable(){
myTable = $('#testTable').dataTable({
"processing": true,
"serverSide": true,
"deferLoading": 0, // here
"ajax": {
"url": "testTableData.html",
"type": "GET",
},
"columns": [
{ "data": "code" },
{ "data": "description" }
]
});
}
要在单击按钮时触发 Ajax,您可以在处理程序中添加类似以下内容的内容:
function buttonClickHandler(event){
$('#testTable').DataTable().draw();
}
请参见下面的示例进行演示。
$(document).ready(function() {
// AJAX emulation for demonstration only
$.mockjax({
url: '/test/0',
responseTime: 200,
response: function(settings){
this.responseText = {
draw: settings.data.draw,
data: [
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "0,800" ]
],
recordsTotal: 1000,
recordsFiltered: 1000
};
}
});
$('#example').DataTable({
"processing": true,
"serverSide": true,
"deferLoading": 0,
"ajax": {
"url": "/test/0",
"type": "GET"
}
});
$('#btn-reload').on('click', function(){
$('#example').DataTable().draw()
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link href="//cdn.datatables.net/1.10.5/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script>
<script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>
</head>
<body>
<p>
<button id="btn-reload">Reload</button>
</p>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</body>
</html>
我可以通过传递一个带有 URL 的额外参数来识别事件来解决此问题。
例如,对于加载,我使用 action="load"
作为查询参数初始化数据 table,对于搜索等其他操作,我传递 action="search"
。有了这个,我在后端将能够识别呼叫来源。如果它不是 "load"
,我将提取数据并传递(就像现在的实现一样)。否则(如果 "load")那么我将传递空数据,这将向我显示 "No Data Found"
消息,就好像它没有进行 ajax 调用一样。
这是我的代码 - Table 初始化:
function initTestTable(){
myTable = $('#testTable').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "testTableData.html?action=load",
"type": "GET",
},
"columns": [
{ "data": "code" },
{ "data": "description" }
]
});
}
对于加载以外的事件(例如按钮单击):
var newUrl = 'testTableData.html?action=search';
myTable.api().ajax.url(newUrl).load();
这是我必须在不修改 table init 的情况下进行的,这会导致错误。
感谢@JSelser 和@davidkonrad 的所有建议:)
这就是我最初在页面加载时加载空数据表的方式。然后我使用 eventListener 通过 ajax 加载数据。我找不到任何我只是玩弄它的文档,它就像一个魅力。
ref 文件 - dataTables.js, table-advanced.js
$(document).ready(function(){
option = "I";
// pick a table list or something
$("#dropdownList").on("change", function(){
option = $('option:selected:not(:disabled)',this).val();
if($.fn.DataTable.isDataTable('#table_001')){
$('#table_001').dataTable().fnDestroy();
InitDataTable(option);
}
else{
InitDataTable("disabled");
}
});
//add/delete/update a row maybe?
$("#signupForm #add_btn").on("click",function(e){
if($("#signupForm").valid()){
var oTable1 = $('#table_001').DataTable(); ///load .ajax structure
//Successful Submit!
oTable1.ajax.reload();
$("#note").html(<img src="/images/loading.gif" alt="loading">');
}
});
//On draw occurs everytime you call table.ajax.reload();
$('#table_001').on( 'draw.dt', function () {
if(option !== "I")
var evtname = $('select[name="EVENT"] option:selected:not(:disabled)').text();
if(evtname !== undefined)
$("#event_name").html("The " + evtname + " Signup Sheet").addClass("xs-small");
// keep track of values for table input fields on each draw
$("[aria-controls='table_001'][type='search']").attr('hth_orig',$(" [aria-controls='table_001'][type='search']").val());
//Don't initialize on draw
TableAdvanced.init('table_001','N');
});
var InitDataTable = function(choice){
var oTable1 = $('#table_001').dataTable( {
"processing": true,
"serverSide": true,
"lengthMenu": [10,25,50,100], // records pulldown
"iDisplayLength": 25, // # records to initially display
"ajax": {
"url": "http://www.domain.com",
"data": function (d) { // pass additional
d.user = user;
d.choice = choice;
d.cols = "15"; // TOTAL <td> tags per <tr> tag
},
// Load attendee total and pending total sections
complete: function (d) {
recordstotal = d.responseJSON.recordsTotal;
attendeetotal = d.responseJSON.attendeeTotal;
//console.log(JSON.stringify(d.responseJSON.data));
if ( attendeetotal == '0') {
$("#totalAttendees").html("No one has signed up for this event yet");
}
else {
$("#totalAttendees").html("Event Total: " + attendeetotal + " attendees");
}
$("#add-atn").removeClass("hidden");
}
},
// insert code to execute after table has been redrawn
"fnDrawCallback": function( oSettings ) {
// Column filtering
var table = $('#table_001').DataTable();
$("#table_001 tfoot th").each( function ( i ) { // i = 0,1...
if($.trim($(this).html()) != '') {
save_html = $(this).html();
$(this).empty();
var select = $(save_html)
.appendTo( this )
.on( 'change', function () {
table.column( i, { filter: 'applied' }).search($(this).val()).draw();
});
$("#table_001 tfoot th:eq("+i+") input").val(save_value);
}
});
//console.log($("#table_001 tfoot th").length);
},
"columns": [// set "data" to next sequential number in double quotes
{"data":"0",// Set "name" to field name that will be refd
"name": "skip"},
{"data":"1",
"name": "skip"},
{"data": "2",
"name": "skip"},
{"data":"3",
"name": "lname"},
{"data":"4",
"name": "fname"}
{"data":"5",
"name": "skip"}
],
"columnDefs": [
// what columns should be hidden?
{
"targets": [1], // what element starting with 0
"class":"hidden" // class to attach to <td>
},
// what columns should NOT be sortable?
{
"targets": [0,1,2,5,6,7,8,9,12,13,14],
"sortable": false, // sortable?
},
// what columns should NOT be searchable?
{
"targets": [0,1,2,6,7,8,9,12,13,14],
"searchable": false, // searchable?
}
],
"createdRow": function( row, data, dataIndex ) {
//manipulate the specific column in the row
//$(row).addClass( 'form-group' );
// $('td', row).eq(2).addClass('form-group'); // Added to <td>
},
// Specify initial sort order
"order": [[ '10', "desc" ],[ '11', "desc" ],['3',"asc"],['4',"asc"]]
});
// handle 1st page table load initialization using
TableAdvanced.init('table_001','Y');
});
}
注意:您可以添加一些逻辑来选择默认选项(如果有可用且未禁用的选项)。