[Spring] REST 기초 - 5 : Ajax - delete(삭제)

 

① : 삭제의 경우 "DELETE" 로 고정 

② : 요청하거나 받은 URL

③ : 전송 데이터

※ ajax를 이용하므로, 전송 데이터를 json 형식으로 지정할 필요가 있음
- JOSON.stringify(전송에 사용될 데이터 변수 명)

④ : 전송 데이터 타입(application/json;charset=utf-8 사용)

 : 전송/수신 성공 시 수행 할 동작이나 callback 함수 사용

- function(data)의 data는 수신 받은 데이터를 저장함

 : 전송/수신 실패 시 수행 할 동작이나 callback 함수 사용(주로 오류 출력)


- 사용 controller

1
2
3
4
5
6
    //Ajax로 delete 요청을 받은 경우 처리함을 
    @DeleteMapping(value = "/{bno}")
    public ResponseEntity<String> deleteSample(@PathVariable("bno") Long bno){
        log.info("update deleteSample");
        return  mapper.delete(bno)==1 ? new ResponseEntity<String>("success", HttpStatus.OK) : new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
cs


- 사용 자바 스크립트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function deleteSample(bno, callback, error){
        console.log("deleteSample")
        $.ajax({
            type : 'delete',
            url : '/sample/'+bno,//별도의 데이터 전송 없이 url 에 값을 담아 전송(get 방식)
            success : function(deleteresult, status){
                if(callback){
                    callback(deleteresult);
                }
            },
            error : function(err){
                if(error){
                    error(er)
                }
            }
        
        })
    }
cs


- 사용 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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id = "sampletest">
<input type="hidden" name="bno" value="${board.bno}">
title : <input type="text" name="title" value="${board.title}"><br>
content : <input type="text" name="content" value="${board.content}"><br>
writer : <input type="text" name="writer" value="${board.writer}"><br>
</div>
 
<button id="sampleBtnUpdate">갱신</button>
<button id="sampleBtnDelete">삭제</button>
</body>
<script src="http://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="/resources/js/sampleTest.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        
        . . .(생략)
    
        //"삭제 버튼 클릭시 수행"
        $("#sampleBtnDelete").on("click",function(e){
            var divtest = $("#sampletest")    
            var bno = divtest.find("input[name=bno]")
            testService.deleteSample(bno.val(),function(){
                window.location.href = '/'// 삭제 후 home 페이지로 
            })
        })
    })
 
</script>
</html>
cs

댓글