ajax2.html

팡태(❁´◡`❁)·2021년 12월 13일
0

html/css/javascript

목록 보기
6/20
<!DOCTYPE html>
<html lang="en">
<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>ajax2.html</title>
    <link href="css/mystyle1.css" rel="stylesheet" />

</head>
<body>
    <div class="container3">
        <h3>생존자</h3>
        <table border="1">
            <thead></thead>
            <tbody></tbody>
        </table>
        <hr />

        <h3>사망자</h3>
        <table border="1">
            <thead></thead>
            <tbody></tbody>
        </table>
    </div>
    <script>
        const url = "https://raw.githubusercontent.com/IBM/taxinomitis/master/resources/datasets/numbers/titanic.json";
        let xhr = new XMLHttpRequest();  // 호출하기 위한 라이브러리
        xhr.open('GET', url)   // 호출주소
        xhr.send();     // 호출

        xhr.addEventListener('load', function(){   // Listener -> 로드되는 타이밍을 모르니까 기다리는거임
            const data = JSON.parse(xhr.response)  // JSON.parse(@@@) string타입을 object로 바꿈
            const fields = data.metadata.fields;

            const thead = document.getElementsByTagName("thead");

            let th = "<tr>";
            for(let tmp of fields){            // 필드의 tmp
                th += `<th>${tmp.name}</th>`;  // tmp의 name 불러오기
            }
            th += '</tr>';
            thead[0].innerHTML = th;
            thead[1].innerHTML = th;

            const tbody = document.getElementsByTagName("tbody");

            const s0 = data.data.survived;
            for(let tmp of s0){
                tbody[0].innerHTML +=
                    "<tr>" +
                        `<td>${tmp[0]}</td>` +
                        `<td>${tmp[1]}</td>` +
                        `<td>${tmp[2]}</td>` +
                        `<td>${tmp[3]}</td>` +
                        `<td>${tmp[4]}</td>` +
                        `<td>${tmp[5]}</td>` +
                        `<td>${tmp[6]}</td>` +
                    "</tr>";
            }

            const s1 = data.data.did_not_survive;
            for(let tmp of s1){
                tbody[1].innerHTML +=
                    "<tr>" +
                        `<td>${tmp[0]}</td>` +
                        `<td>${tmp[1]}</td>` +
                        `<td>${tmp[2]}</td>` +
                        `<td>${tmp[3]}</td>` +
                        `<td>${tmp[4]}</td>` +
                        `<td>${tmp[5]}</td>` +
                        `<td>${tmp[6]}</td>` +
                    "</tr>";
            }
        });
    </script>
</body>
</html>

0개의 댓글