DataTable 서버 사이드 CSV 전체 다운로드
- FRONTEND/Jquery
- 2019. 12. 10. 17:08
이번에 서버 사이드로 DataTable을 이용해 테이블을 만들다가 DataTable에서 지원해주는 CSV다운로드 기능도 사용하게 되었는데 프런트 사이드는 전체 행을 다운로드할 수 있지만 서버 사이드로 할 때에는 일부의 행만 다운로드가 가능했습니다.
대략적인 이유는 아래와 같은데..
According to DataTables documentation there is no way to export all rows when you are using server side:
Special note on server-side processing: When using DataTables in server-side processing mode (serverSide) the selector-modifier has very little effect on the rows selected since all processing (ordering, search etc) is performed at the server. Therefore, the only rows that exist on the client-side are those shown in the table at any one time, and the selector can only select those rows which are on the current page.
구글에서 검색해서 찾아보니 buttons.exportData() 라는 함수에 데이터를 형식에 맞게 리턴해주면 전체 행을 다운로드할 수 있었습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
$(document).ready(function () {
$.fn.DataTable.Api.register( 'buttons.exportData()', function ( options ) {
var arr = [];
$.ajax({
url: '/csvData',
type: 'post',
success: function (result) {
for (var key in result) {
arr.push(Object.keys(result[key]).map(function(k) { return result[key][k] }));
}
},
async: false
});
return {body: arr , header: $("#myTable thead tr th").map(function() { return this.innerHTML; }).get()};
} );
}
|
API 호출해서 리턴 받은 객체 result ↓
1
2
3
4
5
|
[{"id":"id0","first":"first0","second":"second0"},
{"id":"id1","first":"first1","second":"second1"},
{"id":"id2","first":"first2","second":"second2"},
{"id":"id3","first":"first3","second":"second3"},
{"id":"id4","first":"first4","second":"second4"}]
|
1
2
3
4
5
6
7
|
(10) [Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3)]
0: (3) ["id0", "first0", "second0"]
1: (3) ["id1", "first1", "second1"]
2: (3) ["id2", "first2", "second2"]
3: (3) ["id3", "first3", "second3"]
4: (3) ["id4", "first4", "second4"]
|
설명을 하자면 buttons.exportData() 라는 함수에서 Ajax로 전체 데이터를 받아오는 API를 호출해서 데이터를 받아온 후 [ [0,0,0], [1,1,1], [2,2,2] ] 이런 식으로 데이터를 가공해서 body에 넣어주고 header는 DataTable의 thead의 th의 값을 가져와서 리턴해주면 전체행을 다운로드할 수 있습니다.
포스팅 내용이 조금이라도 도움이 되었으면 좋겠습니다.
감사합니다.
'FRONTEND > Jquery' 카테고리의 다른 글
[Jquery] 체크박스 전체 체크 , 해제 하는 방법 (0) | 2020.07.16 |
---|---|
[Jquery] 제이쿼리 a 링크 클릭 방지(#대신) (0) | 2019.04.22 |
[Jquery] 제이쿼리 Input 태그 체크박스, 라디오 상태 체크 및 해제 (0) | 2019.01.08 |
[Jquery] 제이쿼리 체크박스 선택 여부 결정 후 value값 넣기 (2) | 2019.01.08 |
JQuery (0) | 2018.01.17 |