jQuery: DataTables 동적 게시판 라이브러리


웹 애플리케이션 개발 시 자주 사용되는 DataTables 동적 게시판 라이브러리 옵션 설정 및 활용 예제 코드입니다.

1. DataTables 기본 설정 및 Ajax 바인딩

$(function(){
    var table = $('#tbl_userlist');
    userListTable = table.dataTable({
        "stateSave": true,
        "processing": true,
        "serverSide": true,
        "autoWidth": false,
        "bAutoWidth": false,  
        "bPaginate": false,  // 페이징 여부
        "info": false,       // 정보 보이기 여부 

        "language": {
            "emptyTable": "검색된 내역이 없습니다.",
            "info": "<span>검색된 회원</span> <span style='font-weight: bold'>_END_</span> 명 / <span>전체회원</span><b> _TOTAL_ </b>명",
            "infoEmpty": "",
            "infoFiltered": "(filtered1 from _MAX_ total entries)",
            "lengthMenu": "_MENU_ 명 보기",
            "search": "Search:",
            "zeroRecords": "검색된 내역이 없습니다."
        },

        "ajax": { // define ajax settings
            "url": "http://112.175.114.36/admin/index.php/usr/UserSign/ajax_table", // ajax URL
            "type": "POST",
            "data": function(data) {
                SetSearchParams(data);
                data['user_type'] = 0;
                data['user_status'] = 0;
            },
            "dataSrc": function (res) {
                return res.data;
            },
        },

        "columns": [
            {"orderable": false},
            {"orderable": false},
            {"orderable": false},
            {"orderable": false},
            {"orderable": true},
            {"orderable": false},
        ],

        "createdRow": function (row, data, dataIndex) {
            $('td:eq(1)', row).html("<a>" + data["email"] + "</a>");
            $('td:eq(1)', row).bind("click", function() {
                detail(data["uid"], 0);
            });

            $('td:eq(5)', row).html(
                '<a> <i class="fa fa-edit" style="margin-right:10px; color: #26C281" title="편집" id="i_edit"></i>' +
                '<i class="fa fa-check hidden" style="margin-right:10px;" title="승인" id="i_allow"></i>' +
                '<i class="fa fa-close" style="margin-right:10px; color: #E7505A" title="거절" id="i_refuse"></i>' +
                '<i class="fa fa-key" style="color:#F7CA18" title="비밀번호" id="i_prikey"></i></a>'
            );

            if(data['status'] == 0){
                $('td:eq(5)', row).children("a").children("i:eq(1)").addClass("hidden");
            }

            $('td:eq(5)', row).children("a").children("i:eq(0)").bind("click", function () {
                detail(data["uid"], 1);
            });
            $('td:eq(5)', row).children("a").children("i:eq(1)").bind("click", function () {
                allow_user(data["uid"]);
            });
            $('td:eq(5)', row).children("a").children("i:eq(2)").bind("click", function () {
                remove_user(data["uid"], 1);
            });
            $('td:eq(5)', row).children("a").children("i:eq(3)").bind("click", function () {
                setprikey(data["uid"]);
            });
        },

        "order": [],
        "buttons": [],

        "lengthMenu": [
            [10, 20, 50, 100],
            [10, 20, 50, 100],
        ],
        "pageLength": 10,
        "pagingType": 'bootstrap_full_number',
        "dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'i><'col-md-6 col-sm-12'l>r><'table-scrollable't><'row'<'col-md-4 col-sm-12'><'col-sm-12'p>>",
        "fnDrawCallback": function( oSettings ) {
        }
    });
});

2. 리스트 첫칸에 동적으로 번호를 매기는 방법

콜백 함수(fnDrawCallback)를 활용하여 페이지 이동이나 정렬 시에도 순번이 올바르게 계산되도록 처리합니다.

"fnDrawCallback": function( oSettings ) {
    var api = this.api();
    var page = api.page();
    sortable(table.attr('id'), page);
}

// dataTables 번호 넘버링 함수
function sortable(tbl, page){
    var len = $("select[name='"+tbl+"_length']").val() || 0;
    $.each($('#'+tbl+'>tbody>tr'), function(){
        if (!$(this).find('td:first').hasClass('dataTables_empty')){
            var num = parseInt($(this).find('td:first').text());
            $(this).find('td:first').html((page * len) + num);
        }
    });
}

3. 테이블 화면 다시 그리기 (ReDraw)

ListTable._fnReDraw();