$(document).ready(function() {} : 문서가 준비되면 매개변수를 넣은 콜백함수를 실행하라는 의미
여기서는 html파일이 로드되면 alert로 팝업을 띄우게 했다.
3. Ajax(비동기 통신) 및 자바스크립트(Jquery)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script th:inline="javascript">
$(document).ready(function () {
getComments();
})
function getComments() {
var loginUsername = [[${ loginUser }]]
var boardId = $('input[name=boardId]').val()
$.ajax({
type: 'GET',
url: '/board/comment/getCommentList',
data: { boardId },
success: function (response) {
var a = '';
var size = 0;
$.each(response, function (key, value) {
size = size + 1;
a += '<hr /><div>'
a += '<input type="hidden" id="commentId" name="commentId" value="' + value.id + '">'
a += '<span id="writer" style="font-weight: bold;">' + value.writer + '</span>'
if (value.writer == loginUsername) {
a += '<ul name="commentChange" class="justify-content-end" style="display: inline;">'
a += '<li name="commentUpdate" type="button" style="display: inline; opacity: 0.7; font-size: small; margin-right: 5px" onclick="updateCommentForm(' + value.id + ')">수정</li>'
a += '<li name="commentDelete" type="button" style="display: inline; opacity: 0.7; font-size: small;" onclick="deleteComment(' + value.id + ')">삭제</li></ul>'
}
a += '<pre id="' + value.id + '" name="comment' + value.id + '" style="margin-bottom: 5px; font-size: large;">' + value.content + '</pre>'
a += '<p name="createDate' + value.id + '" style="margin-bottom: 5px; opacity: 0.5; font-size: small;">' + value.createDate.substring(0, 10) + ' ' + value.createDate.substring(11, 19) + '</p></div>'
});
$("#count").html(size)
$("#comment").html(a)
},
error: function (response) {
console.log("error : " + response)
},
complete: function () { }
})
}
function updateCommentForm(id) {
var commentId = id;
var content = document.getElementById(id).innerText;
$('ul[name=commentChange]').hide()
$('pre[name=comment' + commentId + ']').contents().unwrap().wrap('<textarea id="newComment" class="form-control mt-2" name="updateContent" rows="4"></textarea>');
$('p[name=createDate' + commentId + ']').contents().unwrap().wrap('<input name="update" type="button" class="me-2 mt-2 btn btn-primary" value="수정하기" onclick="updateComment(' + commentId + ')">');
$('input[name=update]').after("<button class=\"me-2 mt-2 btn btn-primary\" onclick=\"getComments()\">취소</button>")
}
function updateComment(id) {
var commentId = id;
var content = document.getElementById("newComment").value;
$.ajax({
type: 'POST',
url: '/board/comment/update',
data: {
commentId:commentId,
content:content
},
success: function (response) {
getComments()
},
error: function (response) {
console.log("update error : " + response)
},
complete: function () { }
})
}
function deleteComment(id) {
var commentId = id;
if (confirm("정말 삭제하시겠습니까?")) {
$.ajax({
type: 'POST',
url: '/board/comment/delete',
data: { commentId },
success: function (response) {
getComments()
},
error: function (response) {
console.log("delete error : " + response)
},
complete: function () { }
})
} else {
return;
}
}
</script>
댓글 [작성, 수정, 삭제]하는 동시에 페이지를 리로드하지 않고 비동기 통신으로 작성한 댓글을 바로 화면에 보여주는 코드이다. 즉, ajax 통신으로 수정이나 삭제 후 success: 에 getComments()를 호출하면 해당 페이지를 리로드 하지 않고 댓글이 최신화 된다.
<script th:inline="javascript"> : 자바스크립에서 타임리프 변수를 쓰기위해 추가
[[${loginUser}]] : 컨트롤러에서 가져온 로그인해있는 사용자 아이디이다.
$('input[name=id]').val() : input 태그의 name이 id인 값을 가져와서 설정
만약 $('input#idx').val() 이면 input태그의 id값이 idx인것을 가져와서 설정
.val() : form 양식의 값을 설정하거나 가져옴
만약 $('input#idx').val('abc') id가 idx인 input요소의 값을 abc로 설정
url : 서버의 컨트롤러에 호출할 url
data : 넘겨줄 데이터 (여기선 var id)
여기서 들어가는 data 변수 이름은 컨트롤러의 인자명과 같아야 한다.
success : ajax 통신을 성공하고 서버로부터의 결과값을 response에 담아서 함수 실행
$.each(response, function(key, value) {}); : 서버에서 응답받은 데이터의 개수만큼 반복 (for or while)
컨트롤러에서 List<Comment> comments 형태의 객체를 리턴했다.
key는 0, 1, 2, 3 ..
value.content 식으로 데이터 사용 가능. (comments.get(i).getContent와 동일)