main.html
tbody 안에는 js 에서 얻어온 값 동적으로 추가해줄 거라서 비워둠
<table border="1" style="border-collapse: collapse;">
<thead>
<th>번호</th>
<th>할 일 제목</th>
<th>완료 여부</th>
<th>등록 날짜</th>
</thead>
<tbody id="tbody">
</tbody>
</table>
const tbody = document.querySelector("#tbody");
const selectTodoList = () => {
fetch("/ajax/selectList")
@ResponseBody
@GetMapping("selectList")
public List<Todo> selectList() {
List<Todo> todoList = service.selectList();
return todoList;
}
List (Java 전용 타입) 를 반환
-> JS가 인식할 수 없기 때문에
HttpMessageConverter 가 JSON 형태로 변환하여 반환해줄 거임
-> [{ }, { }, { }] JSONArray
.then(resp => resp.text()) // 응답 결과를 text로 변환
.then(result => {
const todoList = JSON.parse(result);
// JS 객체 형태로 변환 K : V
result 는 객체가 아닌 문자열 형태
문자열은 가공은 할 수 있지만 사용하기가 힘듦
JSON.parse(JSON데이터) 이용
반대
JSON.stringify(JS Object) : object -> string
for문 이전에 내용 비워주는 구문 추가
tbody.innerHTML = "";
향상된 for문 이용
for(let todo of todoList) {
// tr 태그 생성
const tr = document.createElement("tr");
// 접근할 때 key 값으로 쓸 거
const arr = ['todoNo', 'todoTitle', 'complete', 'regDate'];
for(let key of arr) {
const td = document.createElement("td");
// 제목인 경우
if(key === 'todoTitle') {
const a = document.createElement("a"); // a태그 생성
// 제목 클릭하면 상세조회 해야해서
a.innerText = todo[key]; // 제목을 a 태그 내용으로 대입한 거 key 가 todoTitle 이니까
a.href = "/ajax/detail?todoNo=" + todo.todoNo;
td.append(a);
tr.append(td);
// a 태그 클릭 시 기본 이벤트(페이지 이동) 막기
// -> 동기 요청이라서
a.addEventListener("click", (e) => {
e.preventDefault(); // 기본 이벤트 막기
// 할 일 상세 조회 비동기 요청
selectTodo(e.target.href);
// e.target.href : 클릭된 a 태그의 href 속성 값을 넘겨줄 거라는 뜻
// "/ajax/detail?todoNo=" + todo.todoNo;
});
continue; // 다음 코드로 넘어가라
}
td.innerText = todo[key];
tr.append(td);
}
// tbody 의 자식으로 tr(한 행) 추가
tbody.append(tr);
}
selectTodoList();