728x90
휴지통 삭제, 복원을 구현하는 방법으로 ajax 통신을 사용하기로 한다.
이 때 체크박스 체크된 게시글만 삭제, 복원 가능하도록 하려고한다.
-> 리스트로 boardId를 서버로 보내서 처리하도록 한다!
1. Controller
// 휴지통 게시글 복원
@PatchMapping("/trash")
@ResponseBody
public void restoreBoards(@RequestParam(name = "boardIdList[]", required = false) List<String> boardIdList) {
for(int i = 0; i < boardIdList.size(); i ++) {
boardService.restore(Long.parseLong(boardIdList.get(i)));
}
}
// 휴지통 게시글 영구 삭제
@DeleteMapping("/trash")
@ResponseBody
public void clearBoards(@RequestParam(name = "boardIdList[]", required = false) List<String> boardIdList) {
for(int i = 0; i < boardIdList.size(); i ++) {
boardService.clear(Long.parseLong(boardIdList.get(i)));
}
}
- @RequestParam(name = "boardIdList[]") : 배열을 List로 받을 것이기 때문에 변수 끝에 대괄호([])를 붙여준다.
2. View
<!-- contents -->
<form class="row g-3 justify-content-end">
<table class="table caption-top table-bordered table-hover">
<caption>List</caption>
<thead>
<tr>
<th class="text-center" width="50" scope="col"></th>
<th class="text-center" width="50" scope="col">No</th>
<th class="text-center" width="950" scope="col">제목</th>
<th class="text-center" width="200" scope="col">작성일</th>
<th class="text-center" width="180" scope="col">작성자</th>
</tr>
</thead>
<tbody>
<tr th:each="board : ${boardList}">
<td class="mt-5 text-center" scope="row">
<div class="checkbox">
<input type="checkbox" name="boardIdList" th:value="${board.id}">
</div>
</td>
<td class="mt-5 text-center" scope="row" th:text="${board.id}">1</td>
<td><a th:text="${board.title}" th:href="@{/board/post(boardId=${board.id})}"
style="text-decoration:none; color:black;">제목</a></td>
<td class="text-center" th:text="${#dates.format(board.createDate, 'yyyy/MM/dd HH:mm')}">작성일
</td>
<td class="text-center" th:text="${board.writer}">작성자</td>
</tr>
</tbody>
</table>
<div class="nav justify-content-end">
<button type="submit" class="btn btn-primary me-2" onclick="restoreBoards()">복원하기</button>
<button type="submit" class="btn btn-danger" onclick="deleteBoards()">삭제하기</button>
</div>
</form>
- form 태그안에 버튼을 생성하고 각 버튼의 onclick을 등록한다.
3. ajax(script코드)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script th:inline="javascript">
// 게시글 복원
function restoreBoards() {
var boardIdList = []
$('input[name="boardIdList"]:checked').each(function (i) {
boardIdList.push($(this).val());
});
if (!isEmptyArr(boardIdList)) {
var param = { "boardIdList": boardIdList }
$.ajax({
url: "/trash",
type: "PATCH",
data: param,
async: false,
success: function (response) {
alert('복원 됐습니다.')
location.reload()
},
error: function (response) {
alert('복원에 실패했습니다.')
}
})
} else {
alert('복원할 게시글을 선택해주세요.')
}
}
// 게시글 삭제
function deleteBoards() {
var boardIdList = []
$('input[name="boardIdList"]:checked').each(function (i) {
boardIdList.push($(this).val());
});
if (!isEmptyArr(boardIdList)) {
var param = { "boardIdList": boardIdList }
$.ajax({
url: "/trash",
type: "DELETE",
data: param,
async: false,
success: function (response) {
alert('영구 삭제 됐습니다.')
location.reload()
},
error: function (response) {
alert('영구 삭제 실패했습니다.')
}
})
} else {
alert('삭제할 게시글을 선택해주세요.')
}
}
// 빈배열 체크
function isEmptyArr(arr) {
if (Array.isArray(arr) && arr.length === 0) {
return true;
}
return false;
}
</script>
- var boardIdList = [] : 자바스크립트 배열 선언
- $('input[name="boardIdList"]:checked').each(function (i) { boardIdList.push($(this).val()); });
- 체크박스에 체크된 개수만큼 each로 반복.
- push를 통해 값을 배열에 초기화
- isEmptyArr : 배열이 비었는지 체크
4. 결과
+ 3번 스크립트 코드 수정!
만약 다중 게시글을 삭제하는데 팝업이 뜨지 않는다면? 당연하다.. 비동기적 통신으로 ajax를 실행해서 그렇다.
이를 해결하려면 동기적으로 ajax 통신을 사용해야하는데, async: false를 ajax 코드에 추가해주면된다.
* ajax 사용하기 : https://black-mint.tistory.com/35
[Spring Boot] Ajax(비동기) 통신으로 댓글 구현 (+ Jquery 사용법)
게시판 댓글을 구현하는 도중 비동기 호출에 대해 알게 됐고, 이를 이용하려면 Ajax를 활용해야 한다는 정보를 얻었다. 비동기란? 비동기의 반대인 동기적 통신의 경우 절차적으로 일을 차례로
black-mint.tistory.com
'Web > SpringBoot' 카테고리의 다른 글
[Spring Boot] Caused by: java.lang.NumberFormatException: For input string: "컬럼 데이터" (오류 해결) (0) | 2022.01.10 |
---|---|
[Spring Boot] Mybatis insert, update 시 PK값 얻기 (0) | 2022.01.09 |
[Spring Boot] 댓글 기능 - REST API 규칙 적용 (0) | 2022.01.06 |
[Spring Boot] 쿠키를 이용한 조회수 구현 (0) | 2022.01.03 |
[Spring Boot] JavaMailSender로 메일 보내기 (0) | 2022.01.03 |