Burninghering's Blog
article thumbnail
Published 2023. 6. 16. 20:42
댓글 기능 구현 - front 패캠 챌린지

ajax.jsp를 복사해서

test.jsp를 만들었다.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
</head>
<body>
<h2>commentTest</h2>
<button id="sendBtn" type="button">SEND</button>
<h2>Data From Server :</h2>
<div id="commentList"></div>
<script>

    let bno = 984;

    let showList = function (bno){
        $.ajax({
            type:'GET',       // 요청 메서드
            url: '/ch4/comments?bno='+bno,  // 요청 URI
            dataType : 'json', // 전송받을 데이터의 타입
            data : JSON.stringify(person),  // 서버로 전송할 데이터. stringify()로 직렬화 필요.
            success : function(result){
                $("#commentList").html(result);    // 서버로부터 응답이 도착하면 호출될 함수
            },
            error   : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
        }); // $.ajax()
    }

    $(document).ready(function(){

        $("#sendBtn").click(function(){
            showList(bno);
        });
    });
</script>
</body>
</html>

 

SimpleRestController.java

맨 위 클래스에 @RestController가 붙으면,

반환 타입이 뷰로 해석되지 않는다.

@Controller 
public class SimpleRestController {
//    @GetMapping("/ajax")
//    public String ajax() {
//        return "ajax";
//    }

    @GetMapping("/test")
    public String test() {
        return "test";
    }

브레이크포인트를 걸고, 잘 들어오는 지 확인도 해봤는데

모두 잘 들어온다 

(댓글들이 html로 나오지 않고 있음)

let toHtml = function (comments){
    let tmp="<ul>";

    comments.forEach(function (comment){
    tmp +='<li data-cno=' +comment.cno
        tmp+='data-pcno='+comment.pcno
        tmp+='data-bno='+comment.bno+'>'
        tmp+='commenter=<span class="commenter>'+comment.commenter+'</span>'
        tmp+='comment=<span class="comment">'+comment.comment+'</span>'
        tmp+='up_date='+comment.up_date
        tmp+='</li>'
    })
    return tmp+"</ul>";
}
let bno = 984;

let showList = function (bno){
    $.ajax({
        type:'GET',       // 요청 메서드
        url: '/ch4/comments?bno='+bno,  // 요청 URI
        dataType : 'json', // 전송받을 데이터의 타입
        success : function(result){
            $("#commentList").html(toHtml(result));
        },
        error   : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
    }); // $.ajax()
}

result라는 배열이 들어오면, toHtml이라는 함수로 li태그로 만들어서 것을 commentList에 넣는 것이다.


삭제 버튼 추가

let toHtml = function (comments){
    let tmp="<ul>";

    comments.forEach(function (comment){
    tmp +='<li data-cno=' +comment.cno
        tmp+='data-pcno='+comment.pcno
        tmp+='data-bno='+comment.bno+'>'
        tmp+='commenter=<span class="commenter">'+comment.commenter+'</span>'
        tmp+='comment=<span class="comment">'+comment.comment+'</span>'
        tmp+='up_date='+comment.up_date
        tmp+='<button class="delBtn">삭제</button>'
        tmp+='</li>'
    })
    return tmp+"</ul>";
}
$(document).ready(function(){

    $("#sendBtn").click(function(){
        showList(bno);
    })

    $("#delBtn").click(function(){
        alert("delBtn clicked")
    })
});

위와 같이 하면, 맨 처음에 del 버튼이 없기 때문에 (send 버튼을 눌러야 del 버튼이 생성되기 때문에)

없으니까 이벤트를 걸 수가 없다.

비동기 요청이기 때문에, 요청이 와야 삭제버튼이 만들어지는데 요청이 오기 전에 실행이 되면 이벤트가 안걸린다.

이벤트를 고정된 요소에 걸어준다.(commentList에)

    $("#commentList").on("click",".delBtn",function(){
        alert("delBtn clicked")
    })
});

위 방법이 동적으로 생성된 요소에 이벤트를 거는 방법!


이제 삭제가 되도록 만들어보자

$("#commentList").on("click",".delBtn",function(){

    let cno=$(this).parent().attr("data-cno"); //버튼의 부모가 li, 부모의 속성 중에 data-cno 가져오기
    let bno=$(this).parent().attr("data-bno");

    $.ajax({
        type:'DELETE',       // 요청 메서드
        url: '/ch4/comments/'+cno+'?bno='+bno,  // 요청 URI
        dataType : 'json', // 전송받을 데이터의 타입
        success : function(result){
            alert(result)
            showList(bno); //삭제된 뒤에 리스트를 가져와서 목록을 갱신해준다
        },
        error   : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
    }); // $.ajax()
})

댓글 쓰기 만들기

comment:<input type="text" name="comment"><br>
    $(document).ready(function(){

        $("#sendBtn").click(function(){
            let comment=$("input[name=comment]").val(); //input 태그에 name이 comment인 것을 comment변수에 담고 그것을 ajax의 stringify로

            $.ajax({
                type:'POST',       // 요청 메서드
                url: '/ch4/comments?bno='+bno,  // 요청 URI
                headers : { "content-type": "application/json"}, // 요청 헤더
                dataType : 'json', // 전송받을 데이터의 타입
                data : JSON.stringify({bno:bno, comment:comment}),  // 서버로 전송할 데이터. stringify()로 직렬화 필요.
                success : function(result){
                    alert(result)
                    showList(bno);
                },
                error   : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
            }); // $.ajax()
        })

공백 입력 못하도록 하기

$(document).ready(function(){

    $("#sendBtn").click(function(){
        let comment=$("input[name=comment]").val(); //input 태그에 name이 comment인 것을 comment변수에 담고 그것을 ajax의 stringify로

        if(comment.trim()==''){ //공백 입력 막기
            alert("댓글을 입력해주세요.");
            $("input[name=comment]").focus()
            return;
        }

        $.ajax({
            type:'POST',       // 요청 메서드
            url: '/ch4/comments?bno='+bno,  // 요청 URI
            headers : { "content-type": "application/json"}, // 요청 헤더
            dataType : 'json', // 전송받을 데이터의 타입
            data : JSON.stringify({bno:bno, comment:comment}),  // 서버로 전송할 데이터. stringify()로 직렬화 필요.
            success : function(result){
                alert(result)
                showList(bno);
            },
            error   : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
        }); // $.ajax()
    })

수정하기 만들기

<button id="modBtn" type="button">수정</button>
$("#commentList").on("click",".modBtn",function() {

    let cno = $(this).parent().attr("data-cno"); //버튼의 부모가 li, 부모의 속성 중에 data-cno 가져오기

    let comment = $("span.comment",$(this).parent()).text();

    //1.comment의 내용을 input에 뿌려주기
    $("input[name=comment]").val(comment);
    //2.cno 전달하기
    $("#modBtn").attr("data-cno",cno);

});
    @PatchMapping("/comments/{cno}")
    public ResponseEntity<String> modify(@PathVariable Integer cno, @RequestBody CommentDto dto,HttpSession session) {
//        String commenter = (String)session.getAttribute("id");
        String commenter = "asdf";
        dto.setCommenter(commenter);
        dto.setCno(cno);
        System.out.println("dto = " + dto);

        try {
            if(service.modify(dto)!=1)
                throw new Exception("Write failed.");
            return new ResponseEntity<>("MOD_OK", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<String>("MOD_ERR", HttpStatus.BAD_REQUEST);
        }
    }
$("#moddBtn").click(function(){
    let cno=$(this).attr("data-cno");
    let comment=$("input[name=comment]").val(); //input 태그에 name이 comment인 것을 comment변수에 담고 그것을 ajax의 stringify로

    if(comment.trim()==''){ //공백 입력 막기
        alert("댓글을 입력해주세요.");
        $("input[name=comment]").focus()
        return;
    }

    $.ajax({
        type:'PATCH',       // 요청 메서드
        url: '/ch4/comments/'+cno,  // 요청 URI
        headers : { "content-type": "application/json"}, // 요청 헤더
        dataType : 'json', // 전송받을 데이터의 타입
        data : JSON.stringify({cno:cno, comment:comment}),  // 서버로 전송할 데이터. stringify()로 직렬화 필요.
        success : function(result){
            alert(result)
            showList(bno);
        },
        error   : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
    }); // $.ajax()
})

'패캠 챌린지' 카테고리의 다른 글

답글 기능 구현  (0) 2023.06.19
댓글 기능 구현 - back  (0) 2023.06.15
REST API와 Ajax  (1) 2023.06.14
게시판 검색 기능 만들기  (0) 2023.06.12
게시판 CRUD 기능 구현_읽기, 삭제  (0) 2023.06.05
profile

Burninghering's Blog

@개발자 김혜린

안녕하세요! 반갑습니다.