본문 바로가기
Code/Web

[JavaScript Code] AJAX 통신을 이용해서 데이터 가져오기

by 스응 2023. 5. 9.
728x90
728x90

코드

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<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>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        .container h1 {
            margin-bottom: 30px;
        }
        .container button {
            padding: 2px 7px;
        }
        .container {
            width: 400px;
            text-align: center;
            border: 3px solid red;
            padding: 10px 0 20px;
        }
        .todos--ul {
            list-style: none;
            text-align: left;
            margin: 20px 30px 0;
        }
 
    </style>
</head>
<body>
    <script>
        let num = 0;
 
        function fetchAjax() {
            // 통신
            $.ajax({
                // 통신 설정 : header, body 설정 등
                type : "get",
                url : `https://jsonplaceholder.typicode.com/todos`,
                contentType : "application/json; charset=utf-8"
 
            }).done((data, textStatus, xhr) => {
                // 통신 성공 시 콜백 들어옴
                let todo = xhr.responseJSON;
                console.log(todo.title);
 
                for (let i = 0; i < 10; i++) {
                    render(i, todo[i].title);
 
                };
 
            }).fail((error) => {
                // 통신 실패  콜백 들어옴
                console.log(error);
 
            });
 
        }
 
        function render(num, title) {
            // 화면 그리는 함수
            let el = $("<li></li>");
            el.attr("id", `li--${num}`);
 
            el.append(`<input type='checkbox' id='check--${num}'>&nbsp;`)
            el.append(`<label for='check--${num}'>${title}</label`);
            el.css("border-bottom""1px solid #ccc");
            el.css("padding""5px 0");
            
            $(".todos--ul").append(el);
            $(`#check--${num}`).on("click"function() {
                if ($(`#check--${num}`).is(":checked")) {
                    $(`#check--${num}`).siblings().css("text-decoration""line-through");
                } else {
                    $(`#check--${num}`).siblings().css("text-decoration""none");
                }
            });
 
        }
 
    </script>
 
 
    <div class="container">
        <h1>To-Do List</h1>
        <button onclick="fetchAjax()">todo 가져오기</button>
        <ul class="todos--ul"></ul>
    </div>
 
</body>
</html>
 
cs

 

실행

 

 

320x100
반응형

댓글