addComment.js
1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import axios from "axios";
const addCommentForm = document.getElementById("jsAddComment");
const commentList = document.getElementById("jsCommentList");
const commentNumber = document.getElementById("jsCommentNumber");
const increaseNumber = () => {
commentNumber.innerHTML = parseInt(commentNumber.innerHTML, 10) + 1;
};
const addComment = (comment) => {
const li = document.createElement("li");
const span = document.createElement("span");
span.innerHTML = comment;
li.appendChild(span);
commentList.prepend(li);
increaseNumber();
};
const sendComment = async (comment) => {
const id = window.location.href.split("/videos/")[1];
const response = await axios({
url: `/api/${id}/comment`,
method: "POST",
data: {
comment, // videoDetail template의 input form's name
},
});
// console.log(response);
if (response.status === 200) {
addComment(comment);
}
};
const handleSubmit = (event) => {
event.preventDefault(); // 새로고침 막기
const commentInput = addCommentForm.querySelector("input");
const comment = commentInput.value;
sendComment(comment);
commentInput.value = "";
};
function init() {
addCommentForm.addEventListener("submit", handleSubmit);
}
if (addCommentForm) {
init();
}