Burninghering's Blog
article thumbnail
Published 2023. 6. 19. 15:06
답글 기능 구현 패캠 챌린지

test.jsp

    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+= ' comment=<span class="comment">'+comment.comment+'</span>'
            tmp+= ' commenter=<span class="commenter">'+comment.commenter+'</span>'
            tmp+= ' up_date='+comment.up_date
            tmp+= ' <button class="delBtn">삭제</button>'
            tmp+= ' <button class="modBtn">수정</button>'
            tmp+= ' <button class="replyBtn">답글</button>'
            tmp+= '</li>'
        })
        return tmp+"</ul>";
    }
<div id="replyForm">
    <input type="text" name="replyComment">
    <button id="wrtRepBtn" type="button">등록</button>
</div>

답글 등록할 폼을 만들었다


$("#commentList").on("click",".replyBtn",function(){
    //1.replyForm을 옮기고
    $("#replyForm").appendTo($(this).parent()); //li태그 뒤에 붙인다
    
    //2.답글을 입력할 폼을 보여주고
    $("#replyForm").css("display","block");

});

 

$("#wrtRepBtn").click(function(){
    let comment=$("input[name=replyComment]").val();
    let pcno=$("#replyForm").parent().attr("data-cno"); //replyForm의 부모(li)에서 data-cno를 가져와서 pcno에 넣어준다 (답글의 부모)

    if(comment.trim()==''){ //공백 입력 막기
        alert("댓글을 입력해주세요.");
        $("input[name=replyComment]").focus()
        return;
    }
    $.ajax({
        type:'POST',       // 요청 메서드
        url: '/ch4/comments?bno='+bno,  // 요청 URI
        headers : { "content-type": "application/json"}, // 요청 헤더
        dataType : 'json', // 전송받을 데이터의 타입
        data : JSON.stringify({pcno:pcno,bno:bno, comment:comment}),  // 서버로 전송할 데이터. stringify()로 직렬화 필요.
        success : function(result){
            alert(result)
            showList(bno);
        },
        error   : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
    }); // $.ajax()

    //답글을 단 뒤 안보이게 한다
    $("#replyForm").css("display","none")
    $("input[name=replyComment]").val('') //값 비우기
    $("#replyForm").appendTo("body"); //원래 위치로 되돌려놓기 (특정 댓글 밑에 있는 것이 아니라 원래 있던 자리 body 아래에 돌려놓기)
})

답글 기능을 만들었더니 댓글들 맨 아래에 답글이 달린다.

매퍼에서 정렬이 잘못되어서 그렇다!

selectAll

 

고친 후 >>

        SELECT cno, bno, ifnull(pcno,cno) as pcno, comment, commenter, reg_date, up_date
        FROM comment
        WHERE bno = #{bno}
        ORDER BY pcno asc, cno asc;

pcno가 null값일때 cno로 대신하고 거기에 별명을 pcno로 준다.
pcno와 cno로 asc를 해주었더니

바로 아래에 답글이 달린다


댓글과 답글을 구분해보자 

    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+'>'
            if(comment.cno!=comment.pcno)
                tmp+='ㄴ'
            tmp+= ' comment=<span class="comment">'+comment.comment+'</span>'
            tmp+= ' commenter=<span class="commenter">'+comment.commenter+'</span>'
            tmp+= ' up_date='+comment.up_date
            tmp+= ' <button class="delBtn">삭제</button>'
            tmp+= ' <button class="modBtn">수정</button>'
            tmp+= ' <button class="replyBtn">답글</button>'
            tmp+= '</li>'
        })
        return tmp+"</ul>";
    }

답글에 답글을 달았더니 또 맨 아래로 가버린다...

wrt버튼에 data-cno 부분을 data-pcno로 바꾼다

$("#wrtRepBtn").click(function(){
    let comment=$("input[name=replyComment]").val();
    let pcno=$("#replyForm").parent().attr("data-pcno"); //요기 attr 부분을 pcno로 변경

    if(comment.trim()==''){ //공백 입력 막기
        alert("댓글을 입력해주세요.");
        $("input[name=replyComment]").focus()
        return;
    }
    $.ajax({
        type:'POST',       // 요청 메서드
        url: '/ch4/comments?bno='+bno,  // 요청 URI
        headers : { "content-type": "application/json"}, // 요청 헤더
        dataType : 'json', // 전송받을 데이터의 타입
        data : JSON.stringify({pcno:pcno,bno:bno, comment:comment}),  // 서버로 전송할 데이터. stringify()로 직렬화 필요.
        success : function(result){
            alert(result)
            showList(bno);
        },
        error   : function(){ alert("error") } // 에러가 발생했을 때, 호출될 함수
    }); // $.ajax()

    //답글을 단 뒤 안보이게 한다
    $("#replyForm").css("display","none")
    $("input[name=replyComment]").val('') //값 비우기
    $("#replyForm").appendTo("body"); //원래 위치로 되돌려놓기 (특정 댓글 밑에 있는 것이 아니라 원래 있던 자리 body 아래에 돌려놓기)
})

pcno값이 널이었지만 이제 cno값과 맞춰서 들어오기 때문에

pcno가 같은 값들끼리 묶이게 된다 (원래는 cno값으로 자식으로 썼는데, 자식에서 답글을 쓰면 대댓글로 달리지가 않는다)

profile

Burninghering's Blog

@개발자 김혜린

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