Spring Boot To do List 비동기_03 할 일 목록 조회하기

송지윤·2024년 4월 15일
0

Spring Framework

목록 보기
26/65

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>

1. js에 tbody 요소 얻어오기

const tbody = document.querySelector("#tbody");

2. 함수 작성 controller 로 요청 보내기

const selectTodoList = () => {
    
    fetch("/ajax/selectList")

3. Controller 에서 받아서 sql 조회하고 다시 js 로 돌려주기

	@ResponseBody
	@GetMapping("selectList")
	public List<Todo> selectList() {
		
		List<Todo> todoList = service.selectList();
		return todoList;
	}

List (Java 전용 타입) 를 반환
-> JS가 인식할 수 없기 때문에
HttpMessageConverter 가 JSON 형태로 변환하여 반환해줄 거임
-> [{ }, { }, { }] JSONArray

4. Controller 에서 받아온 JSONArray 가공

    .then(resp => resp.text()) // 응답 결과를  text로 변환
    .then(result => {

        const todoList = JSON.parse(result);
        // JS 객체 형태로 변환 K : V

result 는 객체가 아닌 문자열 형태
문자열은 가공은 할 수 있지만 사용하기가 힘듦
JSON.parse(JSON데이터) 이용

JSON.parse(JSON데이터) : string -> object

  • string 형태의 JSON 데이터를 JS Object 타입으로 변환

반대
JSON.stringify(JS Object) : object -> string

  • JS Object 타입을 String 형태의 JSON 데이터로 변환

비동기 요청을 할 때 조회 목록이 아래로 계속 쌓이는 문제 해결

for문 이전에 내용 비워주는 구문 추가

tbody.innerHTML = "";

5. 가공된 todoList 를 하나씩 접근해서 #tbody에 동적으로 추가하기

향상된 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);
        }

6. 함수 정의 끝나고 함수 호출해주기

selectTodoList();

0개의 댓글