본문 바로가기
공부기록/실습

3월 23일 (2) AJAX 정보 받아서 표로 만들기

by project100 2023. 3. 23.
<!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>ajax연습</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <style>
        table,
        th,
        td {
            border: 1px solid rgb(15, 15, 75);
            border-collapse: collapse;
        }

        th {
            background-color: #50586C;
            color: white;
        }

        .r {
            width: 50px;
            text-align: center;
        }

        tr:nth-child(odd) {
            background-color: #DCE2F0;
        }
    </style>
    <script>
        $(function () {
            $.ajax({
                url: "https://jsonplaceholder.typicode.com/albums",
                dataType: "json",
                success: function (result) {
                    for (let i = 0; i < result.length; i++) {
                        let tr_elem = `<tr>
                        <td class="r">${result[i].userId}</td>
                        <td class="r">${result[i].id}</td>
                        <td>${result[i].title}</td>
                        </tr>`;
                        $("#re_data").append(tr_elem);
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            });
        });
    </script>
</head>

<body>
    <table>
        <thead id="re_data">
            <tr>
                <th>userId</th>
                <th>id</th>
                <th>title</th>
            </tr>
        </thead>
    </table>
</body>

</html>