Ajax

mamomi·2022년 10월 26일
0

practice-js

목록 보기
9/10
post-thumbnail

ajax로 데이터 GET! 할 때는 너무 어려웠는데 다 구현하고 나서 보니까 쉬운 것 같다? (아님)

1. [student_list.html]

1) 페이지가 열림과 동시에 특별한 이벤트 없이 학생 목록을 조회하여 화면에 table 형식으로 출력 -http://localhost:3001/student
2) 출력할 항목은 학생번호(id), 이름(name), 학년(grade), 연락처(tel) 만 표시함
3) 학생의 이름을 클릭했을 경우
student_info.html 페이지로 a태그를 사용하여 이동해야 한다. 이 때 학생번호를 id라는 이름의 변수로 넘긴다.

2. [stduent_info.html]

페이지가 열림과 동시에 전달받은 id변수를 수신한다. -> UtilHelper에 만들어 둔 기능 활용
해당 id변수를 활용하여 해당 학생의 모든 정보를 출력한다.
http://localhost:3001/student/id값

index.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .text-success {
            color: #0066ff;
            font-size: 24px;
        }
    </style>
</head>
<body>
    <h1>연습문제</h1>
    <a href="#" id="btn">평균나이 구하기</a>
    <div id="console"></div>
    <script>
        document.querySelector('#btn').addEventListener('click', e => {
            e.preventDefault();
            const xhr = new XMLHttpRequest();
            const method = 'GET';
            const url = "http://localhost:3001/student";

            xhr.onreadystatechange = e => {
                const ajax = e.target;
                
                if (ajax.readyState == XMLHttpRequest.DONE) {
                    if (ajax.status == 200) {

                        const json = JSON.parse(ajax.responseText);
                        console.log(json);
                        
                        const nowYear = new Date().getFullYear();

                        /* 1) 일반 반복문으로 합계 구하기
                        let sum = 0;
                        
                        for (const item of json) {
                            const age = nowYear - new Date(item.birthdate).getFullYear() + 1;
                            sum += age;
                        } */

                        // 2) 배열 탐색으로 합계 구하기
                        const sum = json.reduce((acc,cur) => acc + (nowYear - new Date(cur.birthdate).getFullYear() + 1),0);
                        const avg = sum / json.length;

                        const h1 = document.createElement('h1');
                        h1.classList.add('text-success');
                        h1.innerHTML = `학생들의 평균 나이는 ${avg}세 입니다.`;
        
                        document.querySelector('#console').appendChild(h1);
                    } else {
                        const s = parseInt(ajax.status / 100);
                        let msg = null;
                        if (s == 4) {
                            msg = `[${ajax.status}] ${ajax.statusText} - 요청 주소가 잘못되었습니다.`;
                        } else if (s == 5) {
                            msg = `[${ajax.status}] ${ajax.statusText} - 서버의 응답이 없습니다.`;
                        } else {
                            msg = '알 수 없는 이유로 요청에 실패했습니다.';
                        }
                        alert(msg);
                    }
                }
            };
            xhr.open(method,url);
            xhr.send();
        });
    </script>
</body>
</html>

student_info.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul id="list"></ul>
    <script type="module">
        import ajaxHelper from '../helper/AjaxHelper.js';

        const query = new URLSearchParams(location.search);

        const params = Object.fromEntries(query);
        console.log(params.id);

        (async (e) => {
            let json = null;

            try {
                json = await ajaxHelper.requestAsync(`${'http://localhost:3001/student'}/${params.id}`);
                console.log(json);
            } catch (e) {
                console.error(e);
                alert(`[${e.status}] ${e.text}\n${e.msg}`);
                return;  
            }

            const list = document.querySelector('#list');

            for (const k in json) {
                const li = document.createElement('li');
                li.innerHTML = `<strong>${k}</strong>: ${json[k]}`;
                list.appendChild(li);
            }
        })();
    </script>
</body>
</html>

student_list.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Student List</h1>
    <table border="1">
        <thead>
            <tr>
                <th>학생번호</th>
                <th>이름</th>
                <th>학년</th>
                <th>연락처</th>
            </tr>
        </thead>
        <tbody id="list-body"></tbody>
    </table>
    <script type="module">
        import ajaxHelper from '../helper/AjaxHelper.js';

        (async (e) => {
            let json = null;

            try {
                json = await ajaxHelper.requestAsync('http://localhost:3001/student');
                console.log(json);
            } catch (e) {
                console.error(e);
                alert(`[${e.status}] ${e.text}\n${e.msg}`);
                return;  
            }

            const listBody = document.querySelector('#list-body');

            json.forEach((v,i) => {
                const tr = document.createElement('tr');

                const td1 = document.createElement('td');
                td1.innerHTML = v.id;

                const td2 = document.createElement('td');
                const a = document.createElement('a');
                a.setAttribute('href',`student_info.html?id=${v.id}`);
                td2.appendChild(a);
                a.innerHTML = v.name;

                const td3 = document.createElement('td');
                td3.innerHTML = v.grade;

                const td4 = document.createElement('td');
                td4.innerHTML = v.tel;

                tr.appendChild(td1);
                tr.appendChild(td2);
                tr.appendChild(td3);
                tr.appendChild(td4);

                listBody.appendChild(tr);
            });
        })();
    </script>
</body>
</html>


profile
되고 싶다. 나는. 멋진 개발자가.

0개의 댓글

관련 채용 정보