오늘은
1. 댓글을 등록할 수 있는 창
Javascript: save
Python: POST
2. 등록한 댓글이 보이는 테이블
Javascript: show
Python: POST
3. 각 댓글을 삭제할 수 있는 기능
Javascript: delete, ajax
Python: POST(update)
을 구현할 예정이다.
정확하게 말하면 댓글 '삭제' 기능은 아니고 댓글 안보이게 만들기이다 ㅋㅋ
아래 링크를 참고하여 만들었다.
링크텍스트
1) 중요한 포인트: script 시작 시 꼭 아래 코드가 들어가야 한다. 자꾸 빼먹고 안넣으니 테이블이 안나와서 2시간 날림..
$(document).ready(function () {
show_comment();
});
2) 구현 원리
2-1) 저장한 댓글의 doc에 고유 번호와 안보이게 할 수 있는 수(0과1)를 넣는다.
2-2) 그 후 show에서 ajax 코드를 넣어 for문을 넣고 temp_html에 if 조건문을 넣어 삭제 버튼을 넣는다.
2-3) function delete를 넣고 고유 번호를 받아와 삭제할 수 있게한다.
여기서 ajax는 구글링해서 얻은 정보이므로 정확한 해석이 어려웠다...
python : POST (저장)
@app.route("/guestbook", methods=["POST"])
def guestbook_post():
name_receive = request.form['name_give']
comment_receive = request.form['comment_give']
comment_list = list(db.fan.find({},{'_id':False}))
count = len(comment_list) + 1
doc = {
'num': count,
'name': name_receive,
'comment': comment_receive,
'done':0
}
db.fan.insert_one(doc)
python : GET (보여주기)
@app.route("/guestbook", methods=["GET"])
def guestbook_get():
all_comments = list(db.fan.find({},{'_id':False}))
return jsonify({'result':all_comments})
python : POST (안보이게 하기)
@app.route("/guestbook/done", methods=["POST"])
def delete_comment():
num_receive = request.form['num_give']
db.fan.update_one({'num':int(num_receive)},{'$set':{'done':1}})
return jsonify({'msg': 'delete완료'})
script : 저장
function save_comment() {
let name = $('#name').val()
let comment = $('#comment').val()
let formData = new FormData();
formData.append("name_give", name);
formData.append("comment_give", comment);
fetch('/guestbook', { method: "POST", body: formData, }).then((res) => res.json()).then((data) => {
alert(data["msg"]);
window.location.reload()
});
}
script : 보여주기
function show_comment() {
$.ajax({
type: 'GET',
url: '/guestbook',
data: {},
success: function (response) {
let rows = response['result']
$('#comment-list').empty();
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']
let temp_html = ``
if (done == 0) {
temp_html = `<tr>
<td>${name}</td>
<td>${comment}</td>
<td><button onclick="delete_comment(${num})" type="button" class="btn-light">X</button></td>
</tr>`
} else {
temp_html = ``
}
$('#comment-list').append(temp_html)
}
}
})
}
script : 삭제하기
function delete_comment(num){
$.ajax({
type: "POST",
url: "/guestbook/done",
data: {num_give:num},
success: function (response) {
alert(response["msg"])
window.location.reload()
}
});
}
database에서 완전히 삭제할 수 없다는게 아쉽다..