댓글삭제기능(feat. ajax, python)

bebrain·2022년 11월 2일
2
post-thumbnail
  1. Python처리

댓글을 삭제하려면 먼저 댓글을 달 때 순번을 붙여줘야 한다.
(첫번째 단 댓글은 1번, 두번째 댓글은 2번 이런식으로)

len()함수 : 문자열, 배열, 목록 등의 길이를 반환한다.

예시)

languages = ['Python', 'Java', 'JavaScript']

# compute the length of languages
length = len(languages)
print(length)

# Output: 3

len()안에 댓글항목인 comment_list를 넣고
count로 정의해주었다.

여기서 댓글을 달 때 순번은 이전 항목 + 1번째이기 때문에 반드시 +1을 넣어준다.

comment_list = list(db.ha.find({}, {'_id': False}))
count = len(comment_list) + 1

num으로 지정하여 넣어주고
후에 삭제할 항목(1)과 삭제하지 않는 항목(0)을 구분하기 위해 done 지정
그리고 db에 저장

doc = {
        'num':count,
        'name':name_receive,
        'comment':comment_receive,
        'done':0
    }
db.ha(임의지정).insert_one(doc)
return jsonify({'msg':'저장 완료!'})

최종적으로 post는 이렇게 정리된다

@app.route("/ha", methods=["POST"])
def ha_post():
    name_receive = request.form['name_give']
    comment_receive = request.form['comment_give']

    comment_list = list(db.ha.find({}, {'_id': False}))
    count = len(comment_list) + 1

    doc = {
        'num':count,
        'name':name_receive,
        'comment':comment_receive,
        'done':0
    }
    db.ha.insert_one(doc)
    return jsonify({'msg':'저장 완료!'})
  1. Html 처리

Get항목)

rows로 정의한 배열(댓글)을 for반복문을 이용하여 작성자, 댓글내용, 댓글번호, 삭제여부(done)을 차례대로 불러준다

<script>
function show_comment(){
            $.ajax({
                type: 'GET',
                url: '/ha',
                data: {},
                success: function (response) {
                    let rows = response['comments']
                    for (let i = 0; i < rows.length; i++) {
                        let name = rows[i]['name']
                        let comment = rows[i]['comment']
                        let num = rows[i]['num']
                        let done = rows[i]['done']

댓글영역을 temp_html로 정의한 후 비워놓고 시작.
if문을 활용하여 기본댓글(삭제X)은 done=0값으로 지정.(삭제할 댓글은 done=1)
삭제버튼을 클릭했을때 해당 순번(${num})의 댓글이 지워질 수 있도록 onclick이벤트를 넣어주는 것도 잊지말자

let temp_html = ``
	if (done == 0) {
		temp_html = `<div class="comment_card">
						<blockquote class="blockquote mb-0">
							<button onclick="delete_comment(${num})" type="button" class="btn-light">X</button>
							<p>${comment}</p>
							<footer class="blockquote-footer">${name}</footer>
						</blockquote>
					</div>`
	} else {
		temp_html = ``
}
$('#comment-list').append(temp_html)

1-1. 다시 Python으로 돌아와 done처리

삭제버튼을 눌렀을때 done값이 1이 되도록 변경
num_receive값을 정수로 받아오는 int()함수 적용

※int()함수
: 전달한 숫자 혹은 문자열, x를 기반으로 정수 값을 돌려준다.
만약 인자가 없다면 기본 값 0을 돌려준다.

@app.route("/ha(임의지정)/done", methods=["POST"])
def delete_comment():
    num_receive = request.form['num_give']
    db.ha.update_one({'num':int(num_receive)},{'$set':{'done':1}})
    return jsonify({'msg': 'delete완료'})

2-1. Html로 돌아와 댓글삭제 이벤트함수 처리(delete_comment)

        function delete_comment(num){
            $.ajax({
                type: "POST",
                url: "/ha/done",
                data: {num_give:num},
                success: function (response) {
                    alert(response["msg"])
                    window.location.reload()
                }
            });
        }

0개의 댓글