비동기로 변경?
타임리프를 사용한다면 서버에서 받아온 데이터로 화면을 그리는 경우가 많을 것이다.
그러다보면 화면 깜박임없이 새로운 데이터로 view를 갱신해야할때가 생긴다.
그럴때 비동기 ajax를 활용해 View 를 갱신한다.
준비
Controller 에 list 라는 key 값에 a,b,c,d 값을 던져주도록 하였다.
@GetMapping("/test") public String test(Model model){ model.addAttribute("list",Arrays.asList("a","b","c","d")); return "/test"; }
이후 view 에서는 list 값을 그려주도록 하였다.
<!doctype html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <title>main</title> <script src="https://code.jquery.com/jquery-3.7.1.js"></script> </head> <body> <ul> <li th:each="val : ${list}"> [[${val}]] </li> </ul> </body> </html>
결과
서버에서 response 된 list 값인 a,b,c,d 가 제대로 그려지는걸 확인 할 수가 있다.
Ajax 만들기
비동기 처리하기에 앞서 변경할 영역의 id 를 지정해준다.
나는 ul 에 test 란 아이디를 주었고 ajax 요청에 사용할 버튼을 추가하였다.
<ul id="test"> <li th:each="val : ${list}"> [[${val}]] </li> </ul> <button onclick="requestAjax()">요청</button>
버튼에 실행될 함수를 만들었다.
response 받은 후에는 test dom을 서버에서 받은 fragment 값으로 변경하도록 하였다.
<script> const requestAjax = ()=>{ $.ajax({ type: "get", url: "/test-ajax", data: {}, success: (fragment)=>{ $('#test').replaceWith(fragment) }, error: (error)=>{ } }) } </script>
test-ajax request 를 받을 controller 를 추가하였다.
request 가 오면 e,f,g,h 를 던져주도록 하여서 view 가 변경될 수 있게 하였다.
return 값은 변경할 view 경로 :: 아이디 를 return 해준다.
@GetMapping("/test-ajax") public String testAjax(Model model){ model.addAttribute("list",Arrays.asList("e","f","g","h")); return "/test :: #test"; }
결과
요청 버튼을 누르니 e,f,g,h로 값이 변경되는걸 확인할 수 있다.