
[ 제이 쿼리로 part 2, Start ! ]

이거 4개는 무조건 고정으로 붙여넣기!! header.mustache 에!!
index.mustache (.done 과 .fail)
통신이 끝나면 done이 실행되고, 통신이 실패한 경우 fail이 실행
(어떤게 실행 되는지 함수 적기)
* 200이 아니면 전부 다 fail로 넘어옴

<script>
$.ajax({
url: "/api/boards",
type: "get"
}).done((res) => {
console.log("통신 성공");
console.log(res);
}).fail((res) => {
console.log("통신 실패");
console.log(res);
});
post 요청이면 (=body가 있으면) contentType, date 2개가 더 들어간다
지금은 get 요청이라 url과 type만!
통신이 실행되는 시간동안은 기다리지 않고 밑으로 내려가서 자기 할 일 (밑에 적힌 코드)을 함 통신이 연결되면(?) done을 실행
[ 성공 화면 확인 ]

통신이 성공했으니 .done 이 실행 되었다.
실패도 띄워보자!
form 태그는 사용하지 않을 것

form 태그는 사용 안 할 것 -> AJAX라서?
json으로 받은 데이터를 가지고 for문 돌린 후 CSR 하자!

[ 코드 참고 ]
{{> layout/header}}
<div class="container p-5">
<table class="table table-striped">
<thead>
<tr>
<th>번호</th>
<th>제목</th>
<th>내용</th>
<th>작성자</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script>
$.ajax({
url: "/api/boards", //서버가 같으면 8080뒤에 있는 주소는 뒤에 것만 적어도 됨
type: "get" // poset면 컨텐트타입, 데이터가 추가로 들어감
}).done((res) => { // 정상(200)이면 done->바디 데이터
console.log("통신 성공");
console.log(res);
}).fail((res) => {
//console.log(res);
alert(res.responseJSON.msg);
// location.herf="/loginForm";
}); // 실패면 다 fail
function getBoard() {
return `<tr id="board-5">
<td>5</td>
<td>제목5</td>
<td>내용5</td>
<td>홍길동</td>
<td>
<div class="d-flex">
<form action="#">
<button class="btn btn-danger">삭제</button>
</form>
<form action="/board/1/updateForm" method="get">
<button class="btn btn-warning">수정</button>
</form>
</div>
</td>
</tr>`;
}
</script>
{{> layout/footer}}

데이터는 현재 javascpript 오브젝트임
render 뿌리기 → for문 돌리면서 render 함수의 값으로 그림 그리는 것
[ index.mustache 전체 코드 ]
{{> layout/header}}
<div class="container p-5">
<table class="table table-striped">
<!-- 컬럼 -->
<thead>
<tr>
<th>번호</th>
<th>제목</th>
<th>내용</th>
<th>작성자</th>
<th></th>
</tr>
</thead>
<tbody id="board-box">
<!-- render의 리턴값을 board-box에 주면 된다-->
</tbody>
</table>
</div>
<script>
$.ajax({
url: "/api/boards",
type: "get"
}).done((res) => {
console.log("통신 성공");
console.log(res);
// 통신 성공했을 때 body 값을 받아서 for문 돌릴 것
// for(board of boardList) { 라는 for문 돌려도 됨
let boardList = res.body;
boardList.forEach((board)=>{
$("#board-box").append(render(board));
});
}).fail((res) => {
// console.log("통신 실패");
// console.log(res);
alert(res.responseJSON.msg);
//location.href = "/loginForm";
});
function render(board) {
return `<tr id="board-${board.id}">
<td>${board.id}</td>
<td>${board.title}</td>
<td>${board.content}</td>
<td>${board.author}</td>
<td>
<div class="d-flex">
<button onclick="del(${board.id})" class="btn btn-danger">삭제</button>
<form action="/board/${board.id}/updateForm" method="get">
<button class="btn btn-warning">수정</button>
</form>
</div>
</td>
</tr>`;
}
</script>
{{> layout/footer}}
Share article