AJAX
- JavaScript를 사용하여 서버와 브라우저 간에 비동기적으로 데이터를 교환할 수 있는 통신 기능을 얘기한다.
- 원래는 XML로 데이터를 주고 받았는데 JSON이 나오고 나서 JSON이 더 경량이라 JSON사용
- AJAX를 사용하면 페이지 전체를 새로 고침 하지 않고도 필요한 데이터를 비동기적으로 가져올 수 있다.
CSR(Clinet Side Rendering)
사용자의 브라우저 측에서 모든 렌더링 작업을 처리하는 방식으로,
최소한의 HTML 틀만 클라이언트에게 보내
CSR이 SSR보다 더 통신을 해야되는데도 불구하고 CSR을 기법을 사용하는 이유
→비동기로 하는 이유는 그림을 먼저 그리고 데이터를 가져올 수 있기 때문이다 (ux가 좋다.)

동적인 데이터 안에서도 정적인 부분이 있다.
이것을 통신할 때는 정적인 부분은 미리 다운 받고 동적인 부분은 통신을 통해서 데이터를 받으면서 그린다.
HTML 틀
더미
insert into board_tb(title, content, author) values('제목1', '내용1', '홍길동');
insert into board_tb(title, content, author) values('제목2', '내용2', '홍길동');
insert into board_tb(title, content, author) values('제목3', '내용3', '장보고');
insert into board_tb(title, content, author) values('제목4', '내용4', '장보고');
insert into board_tb(title, content, author) values('제목5', '내용5', '장보고');
insert into board_tb(title, content, author) values('제목6', '내용6', '장보고');
insert into board_tb(title, content, author) values('제목7', '내용7', '임꺽정');
insert into board_tb(title, content, author) values('제목8', '내용8', '임꺽정');
HTMl 기본 틀
<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>

페이지에 접속시 위 화면이 뜬다.
실제 데이터는 서버와 통신을 해서 받는다.
AJAX 통신으로 데이터 가져오기
데이터를 가져오기 위해 통신을 한번 더수행한다.
HTTP 통신과의 구분하기 위해 API 통신이라고 정했다.
ApiUtill<T>
package shop.mtcoding.blog.board;
import lombok.AllArgsConstructor;
import lombok.Data;
// 응답받은 상태와 데이터를 받음
@Data
public class ApiUtil<T> {
private Integer status ; //200,400,404,405
private String msg ; // 성공, 실패 -> 메세지 성공시에는 메세지 필요없음
private T body ; // 타입이 정해져있지 않아 new 때 타입을 정하는 T로 정함
//통신이 성공했을 때
public ApiUtil(T body) {
this.status = 200;
this.msg ="성공";
this.body = body;
}
//통신이 실패했을 때
public ApiUtil(Integer status, String msg) {
this.status = status;
this.msg = msg;
this.body=null; // 실패 시에는 메세지와 상태코드만 필요하기 때문에 바디 데이터는 필요없다.
}
}
BoardApiCotroller
@RequiredArgsConstructor
@RestController
public class BoardApiController {
private final BoardRepository boardRepository;
@GetMapping("/api/boards")
public ApiUtil<?> findAll(HttpServletResponse response) {
List<Board> boardList = boardRepository.selectAll();
return new ApiUtil<>(boardList); // MessageConverter
}
/api/boards 입력

상태 코드가 헤더에 있더라도 실패 시에 실패 사유도 알아야 하기 때문에 바디 데이터에 상태와 메세지도 넣는다.
데이터 화면에 출력하기
JQuery를 이용한 AJAX 통신 요청 문법
$.ajax({
}).done((res)=>{
}).fail((res)=>{
});
Ajax 통신을 이용한 데이터 가져오기
{{> layout/header}}
<div class="container p-5">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<table class="table table-striped">
<thead>
<tr>
<th>번호</th>
<th>제목</th>
<th>내용</th>
<th>작성자</th>
<th></th>
</tr>
</thead>
<tbody id="board-box">
</tbody>
</table>
</div>
<script>
$.ajax({
url: "/api/boards",
type: "get"
}).done((res) => {
console.log("통신 성공");
console.log(res);
// 통신이 성공하면 res에 있는 값을 화면에 뿌려야 해.
let boardList = res.body; // 통신 성공했을 때 바디 값을 받아서
boardList.forEach((board) => {
$("#board-box").append(render(board));
}) // 반복문 돌림
}).fail((res) => {
// console.log("통신 실패");
// console.log(res); // 콘솔.로그를 찍어서 res에 뭐가 들어있는지 확인해보자.
alert(res.responseJSON.msg);
// 로그인이 되지 않았다면? 로그인폼을 보여줘야 하잖아.
location.href = "/loginForm";
}); // 200 떨어지면 done, 200이 아니면 fail로 감. 첫 번째 res는 바디데이터, 두 번째 res는 에러메시지
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