[jQuery] Datatables Ajax 사용하기

unhak·2022년 10월 31일
0

jQuery

목록 보기
1/1
post-thumbnail

Datatables 사용 이유?

DataTables란 데이터를 테이블로 쉽게 표현하고 다양한 기능을 제공하는 라이브러리로 기존에 직접 구현하던 Ajax나 Pagination 기능 등 Datatables에서 제공하는 다양한 기능을 편하고 쉽게 사용할 수 있어 사용하게 되었다.


라이브러리 추가

<script src='<c:out value="${pageContext.request.contextPath}"/>/js/plugins/datatables.min.js'></script>
<script src='<c:out value="${pageContext.request.contextPath}"/>/js/plugins/dataTables.rowsGroup.js'></script>

다운받은 datatables 관련 라이브러리를 jsp에 추가한다.
여기서 dataTables.rowsGroup.js는 td의 rowspan(셀병합)을 위해 추가하였다.


Datatables 공통 모듈

Datatables를 여러 곳에서 사용할 수 있기 때문에 공통으로 모듈화한다.

common.js

$.fn.ajaxDataTable = function (url, data, init, error = null) {
    var setting = {
        "serverSide": true,
        "filter": false,
        "lengthChange": true,
        "paging": true,
        "pagingType": "full_numbers",
        "language": {
        	"infoEmpty" : "검색결과가 없습니다.",
        	"zeroRecords" : "검색결과가 없습니다.",
            "emptyTable": "검색결과가 없습니다.",
            "lengthMenu": "_MENU_",
        },
        "bInfo": false,
        "bLengthChange": true, // n개씩보기
        "lengthMenu": [[10, 20, 30], ["10개 보기", "20개 보기", "30개 보기"]], // 10/20/30 개씩보기
        "order": [[0, "desc"]],
        "searching": false,
        "autoWidth": false, //가로자동
        "scrollX": "100%", 
        "scrollXInner": "100%",
        "ajax": {
            url: url,
            type: "POST",
            data : function(d){
                var tmp = data;
                tmp['pageDraw'] = d.draw;
                tmp['pageStart'] = d.start;
                tmp['pageLength'] = d.length;
                tmp['pageOrder'] = d.order[0].dir; //order[0].column
                return tmp;
            },
            "dataSrc": function (result) {
                if (result.code == 'success') {
                    return result.body;
                } else {
                    alert('통신 실패!!!');
                }
            },
            error: function(xhr, status, err) {
                if (error) {
                    error(status);
                } else {
                    alert('통신 실패!!!');
                }
            }
        },
    };

    var val = $.extend(true, setting, init);
    return $(this).DataTable(val);
};

먼저, 공통화하여 원하는 url, 파라미터 정보 등을 각각 다르게 세팅할 수 있게 하였다.
그리고 서버에서 페이징된 목록을 전달받기 위하여 "serverSide":true를 적용하였고 "ajax"에는 전달받은 정보를 세팅하여 서버에 전달해주고 원하는 리스트를 return 받아 페이징된 화면 정보를 완성하였다.


Datatables 적용하기

Datatables 공통 모듈을 만들었으면 이제 직접 적용해보자.

list.jsp

<script type="text/javascript">
    $(() => {
    	let $table = $('.listTbl').ajaxDataTable("/sys/company/companyList", data, {
            columns: [
                { "data": "rownum"},
                { "data": "cmpyNm",
                    "render": function(data, type, row, meta){
                        let cmpyId = row.cmpyId;
                        return '<a href="/sys/company/detail?cmpyId='+cmpyId+'" class="linkStyleNone">' + row.cmpyNm + '</a>';
                    }
                },
                { "data": "mstrUser" },
                { "data": "cmpyRegNmbr" },
                { "data": "cmpyCnt" },
                { "data": "mstrEmail" },
                { "data": "postAddr" },
                { "data": "useYn" },
                { "data": "createId" },
                { "data": "createDt" },
            ],
            columnDefs: [
                { orderable: false, className: 'listTbl__tbody__td', targets: 0},
                { orderable: false, className: 'listTbl__tbody__td', targets: 1},
                { orderable: false, className: 'listTbl__tbody__td', targets: 2},
                { orderable: false, className: 'listTbl__tbody__td', targets: 3},
                { orderable: false, className: 'listTbl__tbody__td', targets: 4},
                { orderable: false, className: 'listTbl__tbody__td', targets: 5},
                { orderable: false, className: 'listTbl__tbody__td', targets: 6},
                { orderable: false, className: 'listTbl__tbody__td', targets: 7},
                { orderable: false, className: 'listTbl__tbody__td', targets: 8},
                { orderable: false, className: 'listTbl__tbody__td', targets: 9},
            ],
        });
    });
</script>
...
...
<table class="listTbl">
	<thead class="listTbl__thead">
    	<tr class="listTbl__tr">
        <th class="listTbl__thead__th">번호</th>
        <th class="listTbl__thead__th">회사명</th>
        <th class="listTbl__thead__th">대표자명</th>
        <th class="listTbl__thead__th">사업자등록번호</th>
        <th class="listTbl__thead__th">직원수</th>
        <th class="listTbl__thead__th">대표 이메일</th>
        <th class="listTbl__thead__th">주소</th>
        <th class="listTbl__thead__th">사용여부</th>
        <th class="listTbl__thead__th">등록자</th>
        <th class="listTbl__thead__th">등록일</th>
        </tr>
    </thead>
</table>

Datatables 모듈을 적용할 table 태그의 class명과 연결하여 columns에는 서버에서 넘어오는 데이터 변수명을 넣고 columnDefs에는 정렬 및 class명을 넣을 수 있다.
그리고 render 함수를 이용하여 column 데이터의 형태를 바꿀 수 있다.


참고 자료

profile
slowly but steadily🐢

0개의 댓글