Spring Ajax를 활용한 게시판 만들기

강정우·2022년 9월 27일
2

spring

목록 보기
9/25
post-thumbnail

View

이런 화면에서
1. 게시판 불러오기를 클릭하면 DB에 접속하여 바로 뿌려준다.
2. 비동기 삭제버튼을 구현한다.
3. 글쓰기를 클릭하면 작성후 바로 DB에 저장하고 글 목록을 보여준다.
4. 게시판 불러오기를 클릭하면 바로 반영이 되고 다시 글쓰기 버튼을 클릭하면 빈 양식을 보여준다.

1. view ajax

1. 버튼 구현

<div class="panel-heading">
	<button class="btn btn-info" id="loadBoard">게시판 불러오기</button>
	<button class="btn btn-success" onclick="goWrite()">글쓰기</button>
</div>

2. id로 ajax 구현

  • <button>에 ajax를 걸어두는 것이 아닌 id에 .on() 메서드를 이용하여 event를 걸어둔다.
$('#loadBoard').on('click', function(){
	loadList();
});
  • loadList 함수 구현
function loadList(){
	$.ajax({
		url : "list.do",
		method : "post",
		dataType : "json",
		success : listBoard,
		error : function(e){
			console.log(e);
		}
	});
}
  • listBoard 함수 구현
    우선 뿌려줄 틀을 boardList.jsp 에서 가져오도록 한다.
function listBoard(data){
	var html = `<table class="table table-hover table-bordered">
						<tr class = "info">		
							<td>글번호</td>
							<td>제목</td>
							<td>작성자</td>
							<td>작성일</td>
							<td>조회수</td>
							<td>삭제</td>
						</tr>`;
						
	for(var i =0; i<data.length; i++){
		html += "<tr>";
		html += "<td>"+(i+1)+"</td>";
		html += "<td>"+data[i].title+"</td>";
		html += "<td>"+data[i].count+"</td>";
		html += "<td>"+data[i].writer+"</td>";
		html += "<td>"+data[i].indate+"</td>";
		html += "<td><button class='btn btn-sm btn-warning' onclick='goDel("+data[i].idx+")'>삭제</button></td>";
		html += "<tr>";
	}
	html += "</tabel>";
	$('.list').html(html);
	$('.list').css("display","block");
	$('.write').css("display","none");
}

<c:forEach>로 감싸져 있던 for문을 풀어서 작성한 모습이다.

2. 삭제

  • 위에서 삭제 버튼까지 구현을 하였다. 이제 이 버튼이 동작되록 Controller와 함수를 추가하도록 하자
function goDel(idx){
	$.ajax({
		url : "delete.do",
		method : "post",
		data : {"idx" : idx},
		success : loadList,
		error : function(e){
			console.log(e);
		}
	});
};
  • Controller
@RequestMapping("/delete.do")
@ResponseBody public void delete(int idx){
	mapper.boardRemove(idx);
}

3. 글작성, serialize()

  • ajax를 이용하여 데이터를 주고 받다 보면 Form 태그 하위에 있는 값들을 한꺼번에 전송해야 할 때가 있다. Form 태그내의 항목이 많지 않다면 일일이 각 항목의 value 값을 읽어와 넘길수 있겠지만, Form 태그내의 모든 항목을 전송한다고 하면 굳이 그럴 필요는 없다.
  • jQuery에서는 serialize() 라는 메소드를 제공하는데, 해당 메소드를 사용하면 Form 태그내의 항목들을 자동으로 읽어와 queryString 형식으로 변환시켜 준다.
    즉. title=안녕&writer=호두아빠&content=반가워요 이런식으로 변환하여 주는데, 이 값을 ajax 호출시 data 속성에 넣어 ajax 통신을 하면 된다.
<script type="text/javascript">
	function goInsert(){
		var frmData = $('#frm').serialize();
		$.ajax({
			url : "insert.do",
			method : "post",
			data : frmData,
			success : loadList,
			error : function(e){
				console.log(e);
			}
		});
	}
    ...
@RequestMapping("/insert.do")
@ResponseBody public void insert(Board board) {
	mapper.boardInsert(board);
}
profile
智(지)! 德(덕)! 體(체)!

0개의 댓글