반응형

이번 글에서는 저번에는 XMLHttpRequest()를 통해 API로 던졌는데, 이번 글에서는 fetch()를 사용하여 데이터를 가져오는 방법에 대해 글을 기록한다.

 

2022.12.23 - [IT/AG Grid] - [AG Grid] AG Grid 데이터 가져오는 방법

 

[AG Grid] AG Grid 데이터 가져오는 방법

이번 글은 AG Grid를 적용하고, 프론트 단에서 백엔드 단으로 API 송신을 하여 데이터를 가져오는 방법에 대해 기록한다. 기존 솔루션에 적용되어 있는 방법과는 확연하게 달라 기록한다. 기존 솔

yongku.tistory.com

 

저번 글은 위의 URL을 참고하면 된다.


AG Grid 기본 세팅

initGrid: function(){
                let _this = this;
                _this.gridOptions = {
                    columnDefs: [
                        {
                            minWidth: 50,
                            headerCheckboxSelection: true,
                            checkboxSelection: true,
                        },
                        {headerName:"USERID", field: "USERID", width: 150, minWidth:120, suppressSizeToFit: true, suppressMenu: true, sort: 'asc'},
			{headerName:"NMLAST", field: "NMLAST", width: 150, minWidth:120, suppressSizeToFit: true, suppressMenu: true, sort: 'asc'},
                    ],
                    defaultColDef: {
                        flex: 1,
                        minWidth: 200,
                        sortable: true,
                        resizable: true,
                        editable: true,
                        floatingFilter: true,
                    },
                    rowSelection: 'multiple',
                    editType: 'fullRow',
                    onRowValueChanged: _this.onRowValueChanged,
                    onSelectionChanged: function(){

                    }
};

 

document.addEventListener('DOMContentLoaded', () => {
                    const gridDiv = document.querySelector('#myGrid');
                    _this.agGrid = new agGrid.Grid(gridDiv, _this.gridOptions);
                    fetch("/common/search/json/data2.json")
                        .then((response) => response.json())
                        .then((data) => _this.gridOptions.api.setRowData(data.data));
});

 

브라우저가 HTML을 전부 일고 DOM 트리를 완성하면 위와 같이, 호출 URL을 통해 데이터를 가져오고 그리드에 뿌린다.

 

검색 function

검색 버튼을 눌렀을 때, 작동하는 function이다. 

let param = inputList.setRangeParam("searchArea");

 

위의 코드는 searchArea에 있는 모든 값들을 가져와서 {KEY : VALUE} 형식으로 param이라는 변수에 넣는다.

 

fetch("/common/search/json/data2.json", {
            		method : 'POST',
            		postData: param2,
            		headers: {
    					'Content-Type': 'application/json',
            		},
            		body: JSON.stringify(param.map),
            	})
                .then((response) => response.json())
                .then((data) => GRID.gridOptions.api.setRowData(data.data));

 

여기서는 자바스크립트 fetch() 함수를 사용한다. fetch() 함수는 브라우저에 내장된 API 호출 함수다. 위와 같이, 호출 URL을 넣고 중괄호를 열어 옵션 객체를 넣고 Promise 객체를 반환한다. API 호출을 성공적으로 했다면 response를 받고, 받은 데이터를 AG Grid에 setRowData를 사용하여 데이터를 뿌려준다.

 

searchList: function() {
            	let _this = this;
            	let param = inputList.setRangeParam("searchArea");
                //아래와 같은 형식으로 KEY : VALUE 형태로 있어야 함.
            	//const tt = {USERID : 'TESTYG'};
            	
            	fetch("/common/search/json/data2.json", {
            		method : 'POST',
            		postData: param2,
            		headers: {
    					'Content-Type': 'application/json',
            		},
            		body: JSON.stringify(param.map),
            	})
                .then((response) => response.json())
                .then((data) => GRID.gridOptions.api.setRowData(data.data));
}

 

전체 코드

<script>
const GRID = {
            agGrid: null
            , gridOptions: null
            , init: function(){
                this.initGrid();
            }
            , initGrid: function(){
                let _this = this;
                _this.gridOptions = {
                    columnDefs: [
                        {
                            minWidth: 50,
                            headerCheckboxSelection: true,
                            checkboxSelection: true,
                        },
                        {headerName:"USERID", field: "USERID", width: 150, minWidth:120, suppressSizeToFit: true, suppressMenu: true, sort: 'asc'},
			{headerName:"NMLAST", field: "NMLAST", width: 150, minWidth:120, suppressSizeToFit: true, suppressMenu: true, sort: 'asc'},
                    ],
                    defaultColDef: {
                        flex: 1,
                        minWidth: 200,
                        sortable: true,
                        resizable: true,
                        editable: true,
                        floatingFilter: true,
                    },
                    rowSelection: 'multiple',
                    editType: 'fullRow',
                    onRowValueChanged: _this.onRowValueChanged,
                    onSelectionChanged: function(){

                    }
                };

                document.addEventListener('DOMContentLoaded', () => {
                    const gridDiv = document.querySelector('#myGrid');
                    _this.agGrid = new agGrid.Grid(gridDiv, _this.gridOptions);
                    fetch("/common/search/json/data2.json")
                        .then((response) => response.json())
                        .then((data) => _this.gridOptions.api.setRowData(data.data));
                });
            }
            , searchList: function() {
            	let _this = this;
            	let param = inputList.setRangeParam("searchArea");
            	let param2 = param.jsonString();
                //아래와 같은 형식으로 KEY : VALUE 형태로 있어야 함.
            	//const tt = {USERID : 'TESTYG'};
            	
            	fetch("/common/search/json/data2.json", {
            		method : 'POST',
            		postData: param2,
            		headers: {
    					'Content-Type': 'application/json',
            		},
            		body: JSON.stringify(param.map),
            	})
                .then((response) => response.json())
                .then((data) => GRID.gridOptions.api.setRowData(data.data));
            }
        }
        
        GRID.init();
        window.GRID = GRID;
</script>
반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기