언어&프레임워크

[웹개발종합반] fetch 연습하기

밍풀 2023. 2. 6. 00:20

http://spartacodingclub.shop/sparta_api/seoulair

Fetch 의 기본골격(데이터를 가져오는 url이 있을때, 그 데이터를 가져오는)

위와 같이 미세먼지 openAPI데이터를 위와 같은 방법으로 가져올 수 있음

1
2
3
4
fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
            console.log(data)
        })
        //url가져와서 json형태로 만들어 그거가지고 무얼무얼해란뜻
cs

 

콘솔창 결과

 

위와 같이 입력시 중구에 대한 데이터만 가져오기도 가능해짐

콘솔창

 

위와 같이 구의 이름만 따로 출력도 가능

 

forEach문이 배열에 있는 원소 하나씩 출력하도록 되어있고, 

위 배열안에 객체가 왼쪽 위 그림과 같이 원소로 들어있기 때문에 객제의 key 값인 'MSRSTE_NM'을 입력해 구 만 뽑아냄

 

미세먼지 data를 가지고 html에 붙여주기

 

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
 
 
//fetch연습
<!doctype html>
<html lang="ko">
 
<head>
    <meta charset="UTF-8">
    <title>미세먼지 API로Fetch 연습하고 가기!</title>
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
 
    <style type="text/css">
        div.question-box {
            margin: 10px 0 20px 0;
        }
        .bed{
            color: red;
        }
    </style>
 
    <script>
        function q1() {
            fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
                let rows = data["RealtimeCityAir"]["row"]
                $('#names-q1').empty()//id names-q1에 달린 태그 모두 제거 
                rows.forEach((a)=>{
                    let gu_mise = a["IDEX_MVL"]//미세먼지농도
                    let gu_name = a["MSRSTE_NM"]//구이름
 
                    //미세먼지 농도 40 넘으면 빨간색으로 표시하도록 스타일 입히기위함
                    let temp_html=``;
                    if(gu_mise>40){
                        temp_html=`<li id="bed">${gu_name} : ${gu_mise}</li>`
                    }else{
                        temp_html =`<li>${gu_name} : ${gu_mise}</li>`
                    }
                    $('#names-q1').append(temp_html);//태그붙여주기
                })
            })
        }
    </script>
 
</head>
 
<body>
    <h1>Fetch 연습하자!</h1>
 
    <hr />
 
    <div class="question-box">
        <h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
        <p>모든 구의 미세먼지를 표기해주세요</p>
        <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
        <button onclick="q1()">업데이트</button>
        <ul id="names-q1">
            <li>중구 : 82</li>
            <li>종로구 : 87</li>
            <li>용산구 : 84</li>
            <li>은평구 : 82</li>
        </ul>
    </div>
</body>
 
</html>
cs

 

업데이트 버튼 클릭시 아래와 같이 구 이름과 미세먼지 농도이름이 나옴

 

 

서울시 따릉이 데이터 가지고 fetch연습

 

 

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
96
97
98
99
100
101
102
103
104
105
106
107
<!doctype html>
<html lang="ko">
 
<head>
    <meta charset="UTF-8">
    <title>Fetch 연습하고 가기!</title>
    <!-- JQuery를 import 합니다 -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 
    <style type="text/css">
        div.question-box {
            margin: 10px 0 20px 0;
        }
 
        table {
            border: 1px solid;
            border-collapse: collapse;
        }
 
        td,
        th {
            padding: 10px;
            border: 1px solid;
        }
 
        .red{
            color: red;
        }
    </style>
 
    <script>
        function q1() {
            fetch("http://spartacodingclub.shop/sparta_api/seoulbike").then(res => res.json()).then(data => {
                let rows = data["getStationList"]["row"]
                $('#names-q1').empty()
                rows.forEach((a) => {
                    let name = a['stationName']
                    let lack = a['rackTotCnt']
                    let park = a['parkingBikeTotCnt']
                    let temp_html='';
 
                    //정차되어있는 자전거수 5개보다 작으면 빨갛게 하도록
                    if(park<5){
                        temp_html= `
                    <tr class="red">
                    <td>${name}</td>
                    <td>${lack}</td>
                    <td>${park}</td>
                </tr>`
 
                    }else temp_html= `
                    <tr>
                    <td>${name}</td>
                    <td>${lack}</td>
                    <td>${park}</td>
                </tr>`
                    $("#names-q1").append(temp_html)
                })
 
            })
 
        }
    </script>
 
</head>
 
<body>
    <h1>Fetch 연습하자!</h1>
 
    <hr />
 
    <div class="question-box">
        <h2>2. 서울시 OpenAPI(실시간 따릉이 현황)를 이용하기</h2>
        <p>모든 위치의 따릉이 현황을 보여주세요</p>
        <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
        <button onclick="q1()">업데이트</button>
        <table>
            <thead>
                <tr>
                    <td>거치대 위치</td>
                    <td>거치대 수</td>
                    <td>현재 거치된 따릉이 수</td>
                </tr>
            </thead>
            <tbody id="names-q1">
                <tr>
                    <td>102. 망원역 1번출구 앞</td>
                    <td>22</td>
                    <td>0</td>
                </tr>
                <tr>
                    <td>103. 망원역 2번출구 앞</td>
                    <td>16</td>
                    <td>0</td>
                </tr>
                <tr>
                    <td>104. 합정역 1번출구 앞</td>
                    <td>16</td>
                    <td>0</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
 
</html>
 
cs