가자공부하러!

Javascript Full Calendar(3) - DB 값 가져오기 본문

공부/Javascript, Node.js, jQuery, Ajax

Javascript Full Calendar(3) - DB 값 가져오기

오피스엑소더스 2019. 9. 3. 20:45

1. 개발환경


1. 다운로드

  > Javascript Full Calendar 홈페이지 : https://fullcalendar.io

  > Javascript Full Calendar Scheduler : https://fullcalendar.io/docs/premium


2. 실습환경 : Spring Boot 2.1.7, JDK8, JSP, tiles, Full Calendar 4.3.1

 

3. 적용페이지 : src/main/webapp/WEB-INF/views/calendar/calmain.jsp


2. Calendar 외부의 값 가져오기


1. 버튼 클릭 시 이벤트 가져오기

  > 배열 형태

- 예) 2차원 배열

- 보낼 때 : var arr = [ {'title':'evt4', 'start':'2019-09-04', 'end':'2019-09-06'} ];

- 받을 때 : calendar.addEvent( arr[0] );

- 예) 1차원 배열

- 보낼 때 : var arr = { 'title':'evt4', 'start':'2019-09-04', 'end':'2019-09-06' };

- 받을 때 : calendar.addEvent( arr );


3. DB에서 값 가져오기


1. 순서

  > calendar 객체 생성(view - js)

  > ajax통신을 통해 DB CALENDAR 테이블의 데이터를 요청하는 javascript 함수 작성(view - js)

  > ajax통신을 통해 데이터를 Map 타입으로 건네주는 Controller, Service, DAO 작성(java)

  > ajax통신을 통해 받아온 데이터를 calendar 객체에 적용하는 코드 작성

- $.each 함수를 활용해서 calendar에 이벤트 추가


2. 데이터

  > Full Calendar 이벤트 객체가 갖는 필드

- title : 캘린더에 표시되는 일정의 이름

- start : 캘린더에 표시되는 일정의 시작일 (yyyy-mm-dd[THH:MM:SS] ; 2019-09-05T12:30:00)

- end : 캘린더에 표시되는 일정의 마지막 일 (yyyy-mm-dd[THH:MM:SS] ; 2019-09-05T12:30:00)

- 캘린더에는 start부터 end전날까지 표시됨

- allDay : 일정이 종일인지 아닌지 여부(boolean)


3. Controller에서 Map 형태로 보낸 데이터 FullCalendar에 추가하는 방법

  > Map
1
2
3
4
Map<String, FullCalendarDTO> javaMap = new HashMap<String, FullCalendarDTO>();
 
javaMap.put("evt1"new FullCalendarDTO("db이벤트1""2019-09-04""2019-09-06""false") );
javaMap.put("evt2"new FullCalendarDTO("db이벤트2""2019-09-23""2019-09-26""false") );        
cs

  > script (ajax)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function getCalendarDataInDB(){
    var arr = [{title: 'evt1', start:'ssssss'}, {title: 'evt2', start:'123123123'}];
    
    $.ajax({
        contentType:'application/json',
        dataType:'json',
        url:'calendar/getall',
        type:'post',
        async: false,
        success:function(resp){
            arr = resp;
        },
        error:function(){
            alert('저장 중 에러가 발생했습니다. 다시 시도해 주세요.');
        }
    });
    return arr;
}
cs

  > script (Full Calendar 내부 버튼클릭 이벤트)

1
2
3
4
5
6
7
$("#btnAddTest").click(function(){
 var arr = getCalendarDataInDB();
 $.each(arr, function(index, item){
  calendar.addEvent( item );
 });
 calendar.render();
});
cs

 



4. 상세 코드 보기


1. calmain.jsp 전체 코드 보기(접기/펼치기)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href='fullcalendar/core/main.css' rel='stylesheet' />
<link href='fullcalendar/daygrid/main.css' rel='stylesheet' />
<link href='fullcalendar/timegrid/main.min.css' rel='stylesheet' />
<script src='fullcalendar/core/main.js'></script>
<script src='fullcalendar/daygrid/main.js'></script>
<script src="fullcalendar/interaction/main.min.js"></script>
<script src="fullcalendar/timegrid/main.min.js"></script>
<script src='fullcalendar/core/locales/ko.js'></script>
 
<!-- 캘린더 초기 설정 -->
<script>
 
document.addEventListener('DOMContentLoaded', function() {
  var Calendar = FullCalendar.Calendar;
  var Draggable = FullCalendarInteraction.Draggable;
 
  var containerEl = document.getElementById('external-events');
  var calendarEl = document.getElementById('calendar');
  var checkbox = document.getElementById('drop-remove');
 
  // initialize the external events
  // -----------------------------------------------------------------
 
  new Draggable(containerEl, {
    itemSelector: '.fc-event',
    eventData: function(eventEl) {
      return {
        title: eventEl.innerText
      };
    }
  });
 
  // initialize the calendar
  // -----------------------------------------------------------------
 
  var calendar = new Calendar(calendarEl, {
    plugins: [ 'interaction''dayGrid''timeGrid' ],
    header: {
      left: 'prev,next today',
      center: 'title',
      right: 'dayGridMonth,timeGridWeek,timeGridDay'
    },
    editable: true,
    droppable: true// this allows things to be dropped onto the calendar
    drop: function(info) {
      // is the "remove after drop" checkbox checked?
      if (checkbox.checked) {
        // if so, remove the element from the "Draggable Events" list
        info.draggedEl.parentNode.removeChild(info.draggedEl);
      }
    },
    locale: 'ko',
    events: [
        {
            title : 'evt1',
            start : '2019-09-03'
        },
        {
            title    :    'evt2',
            start    :    '2019-09-10',
            end    :    '2019-09-20'
        },
        {
            title    :    'evt3',
            start    :    '2019-09-25T12:30:00',
            allDay    :    false
        }
    ]
  });
 
  calendar.render();
  
  var arrTest = getCalendarDataInDB();
  $.each(arrTest, function(index, item){
        console.log('outer loop_in_cal' + index + ' : ' + item);
        $.each(item, function(iii, ttt){
            console.log('inner loop_in_cal => ' + iii + ' : ' + ttt);
        });
  });
  
  $("#btnAddTest").click(function(){
      //var arr = getCalendarEvent();
      var arr = getCalendarDataInDB();
      //console.log('arr[0].size : ' +  Object.keys( arr[0] ).length );
      $.each(arr, function(index, item){
          calendar.addEvent( item );
          console.log('click evt loop_in_cal' + index + ' : ' + item);
          $.each(item, function(iii, ttt){
                console.log('click evt inner loop_in_cal => ' + iii + ' : ' + ttt);
          });
      });
      
      //calendar.addEvent( {'title':'evt4', 'start':'2019-09-04', 'end':'2019-09-06'});
      calendar.render();
  });  
  //alert( '캘린더에서 알린다!!! 잘 받았다! ' + (arrTest.0.id) );
});
 
function getCalendarEvent(){
    //var arr = [ {'title':'evt4', 'start':'2019-09-04', 'end':'2019-09-06'} ];
    var arr = { 'title':'evt4''start':'2019-09-04''end':'2019-09-06' };
    return arr;
}
 
function getCalendarDataInDB(){
    var arr = [{title: 'evt1', start:'ssssss'}, {title: 'evt2', start:'123123123'}];
    
    //배열 초기화
    var viewData = {};
    //data[키] = 밸류
    viewData["id"= $("#currId").text().trim();
    viewData["title"= $("#title").val();
    viewData["content"= $("#content").val();
    
    $.ajax({
        contentType:'application/json',
        dataType:'json',
        url:'calendar/getall',
        type:'post',
        async: false,
        data:JSON.stringify(viewData),
        success:function(resp){
            //alert(resp.f.id + ' ggg');     
            $.each(resp, function(index, item){
                console.log(index + ' : ' + item);
                $.each(item, function(iii, ttt){
                    console.log('inner loop => ' + iii + ' : ' + ttt);
                });
            });
            arr = resp;
        },
        error:function(){
            alert('저장 중 에러가 발생했습니다. 다시 시도해 주세요.');
        }
    });
    
    return arr;
}
 
</script>
<!-- 캘린더 한글 설정 -->
<script src="js/calendar/calmain.js"></script>
<style>
 
  html, body {
    margin: 0;
    padding: 0;
    font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
    font-size: 14px;
  }
 
  #external-events {
    position: fixed;
    z-index: 2;
    top: 300px;
    left: 140px;
    width: 150px;
    padding: 0 10px;
    border: 1px solid #ccc;
    background: #eee;
  }
 
  .demo-topbar + #external-events { /* will get stripped out */
    top: 60px;
  }
 
  #external-events .fc-event {
    margin: 1em 0;
    cursor: move;
  }
 
  #calendar-container {
    position: relative;
    z-index: 1;
    margin-left: 200px;
  }
 
  #calendar {
    max-width: 900px;
    margin: 20px auto;
  }
 
</style>
 
</head>
<body>
 
<div id="external-events">
    <p>
      <strong>Draggable Events</strong>
    </p>
    <div class="fc-event">My Event 1</div>
    <div class="fc-event">My Event 2</div>
    <div class="fc-event">My Event 3</div>
    <div class="fc-event">My Event 4</div>
    <div class="fc-event">My Event 5</div>
    <p>
      <input type="checkbox" id="drop-remove">
      <label for="drop-remove">remove after drop</label>
    </p>
  </div>
<div id='calendar'></div>
<input type="button" id="btnAddTest" value="추가">
</body>
</html>
cs






Comments