초기 자동 에이잭스 호출 사용 안 함 - DataTable 서버 측 페이징
서버측 페이징으로 초기화된 dataTable이 정상적으로 동작하고 있습니다.이 테이블은 초기화 중에 Ajax를 트리거하고 데이터를 꺼내 테이블 위에 렌더링합니다.단, 처음에 빈 테이블이 필요하고 다음과 같이 load() 또는 reload()를 사용하여 버튼을 클릭했을 때 테이블 데이터를 로드합니다.
myTable.api().ajax.reload();
테이블 초기화는 다음과 같습니다.
function initTestTable(){
myTable = $('#testTable').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "testTableData.html",
"type": "GET",
},
"columns": [
{ "data": "code" },
{ "data": "description" }
]
});
}
초기화 중에 테이블 로드를 제한할 수 있는 방법이 있습니까?서류를 읽었지만 찾을 수 없었다.제안해 주세요.
delayLoading 파라미터를 사용하여 다음과 같이 설정할 수 있습니다.0
필터, 정렬 액션 또는 그리기/재로드 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", "$320,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
[ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,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"
query param 및 검색과 같은 기타 액션에 대해 am passing,action="search"
이것에 의해, 백엔드로 콜의 발신지를 식별할 수 있게 됩니다.이 이외의 것이라면"load"
(현재 구현대로) 데이터를 추출하여 전달하고 있습니다.그렇지 않은 경우('로드'의 경우) 빈 데이터를 전달하고 있습니다.이것에 의해,"No Data Found"
Ajax 콜을 발신하지 않은 것처럼 표시됩니다.
다음은 내 코드입니다 - 테이블 초기화:
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의 제안에 감사드립니다.
페이지 로드에 빈 dataTable을 처음 로드하는 방법입니다.그런 다음 eventListener를 사용하여 Ajax를 통해 데이터를 로드합니다.그냥 가지고 놀던 문서를 찾을 수 없었고 아주 잘 작동합니다.
ref files - 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');
});
}
메모: 사용할 수 있고 비활성화되지 않은 기본 옵션이 있는 경우 기본 옵션을 선택하는 논리를 추가할 수 있습니다.
올바른(작동) 방법은 다음과 같습니다.
$(document).ready(function() {
tableConfig = {
pageLength: 5,
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
};
var table = $('#example').DataTable(tableConfig);
$('#ajaxLoad').on('click', function() {
tableConfig.ajax = {
"url": "ajax/objects_root_array.txt",
"dataSrc": ""
};
table.destroy();
table = $('#example').DataTable( tableConfig );
})
} );
언급URL : https://stackoverflow.com/questions/31175340/disable-initial-automatic-ajax-call-datatable-server-side-paging
'programing' 카테고리의 다른 글
JSON.Net 시리얼라이저가 JsonProperty를 무시합니까? (0) | 2023.04.03 |
---|---|
LINQ를 JSON으로 설정할 수 있습니까? (0) | 2023.04.03 |
제품 코드 구축 방법 및 사용 방법 웹 팩 (0) | 2023.02.12 |
Woocommerce에서 체크아웃 필드를 생성하는 제품 수량에 따른 ACF 리피터 (0) | 2023.02.11 |
css에서 요소를 사용하여 요소가 투영기에 있는지 확인합니다. (0) | 2023.02.11 |