개발자's Life

[JavaScript] DataTable 이용하여 간단한 테이블 만들기 본문

Front-end

[JavaScript] DataTable 이용하여 간단한 테이블 만들기

Rowen Jobs 2023. 7. 28. 17:23
728x90
반응형

DataTable 을 이용하여 간단하게 Table 을 만들 수 있다.

 

백앤드에서 들어오는 데이터는 Json 형태로 다음과 같다

[
    {"col1" : "col_1", "col2" : "col_2", "col3" : "col_3", "col1" : "col_4"},
    {"col1" : "col__2", "col2" : "col_3", "col3" : "col_4", "col1" : "col_5"},
    {"col1" : "col__3", "col2" : "col_4", "col3" : "col_5", "col1" : "col_6"},
    {"col1" : "col__4", "col2" : "col_5", "col3" : "col_6", "col1" : "col_7"},
    {"col1" : "col__5", "col2" : "col_6", "col3" : "col_7", "col1" : "col_8"},
    {"col1" : "col__6", "col2" : "col_7", "col3" : "col_8", "col1" : "col_9"}
]

 

Html 은 비교적 단순하게 적기만 하면되고 아래를 참고하면 된다!

<table id="myTable" style="width:100%">
    <thead style="text-align:center">
        <tr>
            <th>W/O</th>
            <th>PROJECT</th>
            <th>총 생산량</th>
            <th>실제 생산량</th>
            <th>불량 건수</th>
            <th>불량율</th>
        </tr>
    </thead>
</table>

 

col1, col2, col3, col4 키 값이 Columns 키 값 내부  data 로 들어가게 되면 자동으로 맞는 데이터를 출력해준다.

$("#myTable").DataTable({
    scrollX: true, // 가로 스크롤
    scrollY: "50vh", // 세로 높이
    scrollCollapse: true, // true : row 갯수의 의한 테이블 높이를 우선으로 한다, false : scrollY 높이를 우선으로 한다.
    lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "ALL"]],
    pageLength: -1,
    ajax:{
        url : "write_api_call_url",
        type : "POST",
        data: function(data){
        // 데이터 출력 시 필요 파라미터 전달
        data.param1 = $("#user_role").val();
        data.param2 = $("#user_code").val();
    }
    },
    columns: [
        {
            data: "col1",
            className: "dt-body-left", // class 명 지정
            width: "20%"
        },
        {
            data: "col2",
            className: "dt-body-left",
            width: "45%"
        },
        {
            data: col3,
            className: "dt-body-right",
            width: "10%",
            render:function(data, type, row){
            // 출력 데이터 가공 가능 data
            return data;
        }
        },
        {
            data: col4,
            className: "dt-body-right",
            width: "25%"
        }
	]
});

위와 같이 아주 기본적인 기능들만으로 테이블에 데이터 출력까지 완성이 가능하다. 

 

기본적인거 이외에도 기능이 아주 다양하기에 아래 링크에서 필요한 기능을 찾아 사용하면 편리할거 같다.

(기본 설정도 아래 링크에서 확인 가능!)

https://datatables.net/

 

DataTables | Table plug-in for jQuery

DataTables Table plug-in for jQuery Advanced tables, instantly DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any H

datatables.net

 

728x90
Comments