TIL 2023-01-11 항해99 D+3

황원준·2023년 1월 12일

hanghae99

목록 보기
7/24

1. 문제점

상세 페이지를 만들다 보니 CRUD의 내용을 담을려고 하다보니 나의 역량? 한계를 시험하는 거 같았다. 먼저 Create인 코멘트 올리기는 해본적이 있다보니 쉽게 되었는데 DB에서 삭제인 Delete가 되질 않아 굉장히 당황스러웠다.

2. 시도 해본 것들

특히, 이해가 되질 않았다.
분명히,

function posting() {
            if (confirm("코멘트를 저장하시겠습니까?")) {
                let comment = $('#comment').val()

                $.ajax({
                    type: "POST",
                    url: "/posting/comments",
                    data: {comment_give: comment},
                    success: function (response) {
                        alert(response["msg"])
                        window.location.reload()
                    }
                });
            } else {
                alert("취소하였습니다!");
            }
        }
// DB쿼리
@app.route("/posting/comments/delete", methods=["POST"])
def comment_delete():
    comment_receive = request.form['comments_give']

    # query = db.comments.find_one({'comment': comment_receive})

    db.comments.delete_one({'comment': comment_receive})

    return jsonify({'msg': '삭제되었습니다!'})
         
        

여기를 거쳐서 저장취소하면 취소도 나왔고, 저장버튼을 누른다면 "삭제되었습니다!"도 뜨는데 왜 안되는지 이해가 되질 않았다 ㅜㅜ

3. 해결법

function delete_comment(comment) {
            if (confirm("코멘트를 삭제하시겠습니까?")) {
                $.ajax({
                    type: "POST",
                    url: "/comment/delete",
                    data: {comment_give: comment},
                    success: function (response) {
                        alert(response["msg"]);
                        window.location.reload()
                    }
                });
            } else {
                alert("취소하였습니다!")
            }

        }

        function show_comments() {
            $.ajax({
                type: "GET",
                url: "/posting",
                data: {},
                success: function (response) {
                    let rows = response['comments']
                    for (let i = 0; i < rows.length; i++) {
                        let comment = rows[i]['comment'];
                        let number = rows[i]['num'];

                        let temp_html = `<li class="list-group-item d-flex justify-content-between">
                                            <span>${comment}</span>
                                            <button type="button" class="btn btn-danger delete" onclick="delete_comment('${comment}')">삭제</button>
                                         </li>`

                        $('#comments-list').append(temp_html)

                    }
                }
            });
        }

애초에 저 comment는변수값으로받아우리가원하는string값이아니다보니컴퓨터가뱉어내는게계속undefined였던것이었다.그래서deletecomment()함수{comment}는 변수값으로 받아 우리가 원하는 string값이 아니다 보니 컴퓨터가 뱉어내는게 계속 undefined였던 것 이었다. 그래서 delete_comment() 함수에 '{comment}'로 string 문자열로 전환시켜서 삭제버튼을 눌렀을 때 코멘트를 보내는 함수를 만들어 해결하였다.

4. 알게 된 점

undefined가 계속 뜨면 먼저 변수값인지 아니면 출력값이 없는건지 확인해서 숫자면 숫자로 변형, 문자값이면 문자로 변형 출력하게끔 해야할 것 같다.

profile
좋은 개발자가 되기 위해 노력 하는 개린이

0개의 댓글