아침에 댓글 수정기능을 구현했다!
왕초보 웹개발 강의 들을 때 만들었던 방명록에 연습을 해 봤다
이 기능을 구현하며 내가 제일 생각하지 못했던 것은 GET요청의 temp_html로 보여지는 댓글박스를 두가지 경우로 설정하는 것이었다. 이 작업을 위해 새로운 값 edit을 넣어줬다.
초기값은 0으로 설정했다.
이 후 edit이 바뀔때마다 상황을 다르게 설정해야 하므로 edit의 값을 update하는
PUSH 메소드 2개를 작성해줘야 한다. ( 하나는 수정기능, 하나는 수정완료기능)
edit이 2일때 수정창을 뜨게하면 되고 1일때 메인창으로 들어가며 comment를 수정해준다.
이제 html script를 바꿔줘야한다
function show_comment() {
$('#comment-list').empty()
$.ajax({
type: "GET",
url: "/homework",
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 edit = rows[i]['edit']
let temp_html = ``
if (edit == 0 || edit == 1) {
temp_html = `<li><div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>${comment} <button onclick="cmt_del(${num})">삭제</button>
<button onclick="cmt_edit(${num})">수정</button></p>
<footer class="blockquote-footer">${name}</footer>
</blockquote>
</div>
</div>
</li>`
} else {
temp_html = `<li><div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p><input type="text" id="edit_comment" value="${comment}">
<button onclick="cmt_edit_clear(${num})">완료</button></p>
<footer class="blockquote-footer">${name}</footer>
</blockquote>
</div>
</div>
</li>`
}
$('#comment-list').append(temp_html)
for 반복문에 edit을 추가해 같이 돌려줬고 edit이 0이나 1일때는 기본창을, edit이 2일때는
input창을 나오게 하고 벨류값을 기존의 comment로 냅뒀고 완료버튼을 추가해줬다.
다음은 PUSH메소드의 html 코드이다
function cmt_edit(num) {
$.ajax({
type: 'PUSH',
url: '/homework/edit',
data: {num_give: num},
success: function (response) {
alert(response['msg'])
window.location.reload()
}
})
}
// 인풋창 on
function cmt_edit_clear(num) {
let edit_comment = $('#edit_comment').val()
$.ajax({
type: 'PUSH',
url: '/homework/edit_clear',
data: {num_give: num, edit_comment_give: edit_comment},
success: function (response) {
alert(response['msg'])
window.location.reload()
}
})
}
결과는?
잘 작동한다 :)
다만 한가지 수정해야 할 게 있는데 count값을 len으로 줬기때문에 데이터베이스에 저장하고 삭제할때 오류가 뜰 가능성이 있다.
안녕을 순서대로 123까지 데이터베이스에 넣고 2를 삭제하고 4을 입력한 상황이다.
4는 고유넘버 4를 가져야하지만 2가 빠짐으로써 3이라는 넘버를 받기때문에 안녕3과 겹치게된다 .....
이 문제를 해결하려면 mongoDB에서 name위에 있는 고유의 id값을 이용하거나 넘버를 부여해줄때 난수로 해줘야 할 것 같다. 개인적으로 이번 주 내에 해결해보고 싶다.
마지막으로 개인홈페이지 사진하나 올리고
API명세서 올리고
기능 | methods | DATA 경로 | request 요구 | response 호응 |
---|---|---|---|---|
방명록 저장 | POST | /kakhi_cmt | {nick_give: nick, comment_give: comment} | 댓글이 달렸어요! |
방명록 보여주기 | GET | /kakhi_cmt | {} | {'nicks': nick_list} |
방명록 삭제 | POST | /kakhi_cmt/del | {num_give: num} | 삭제 완료! |
방명록 수정 | POST | /kakhi_cmt/edit | {num_give: num} | 수정하시겠습니까? |
방명록 수정완료 | POST | /kakhi_cmt/clear | {num_give: num, edit_give: edit} | 수정 완료! |
팀프로젝트 동영상 링크
동영상