본문 바로가기
스파르타/Web

[Web] fetch 연습 - 미세먼지API ( week 2 )

by bakcoding_sparta 2023. 4. 19.

서울시 미세먼지 OpenAPI

API를 통해서 가져온 데이터를 다루어 본다.

 

JSON Data

<!doctype html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>미세먼지 API로Fetch 연습하고 가기!</title>


    <style type="text/css">
        div.question-box {
            margin: 10px 0 20px 0;
        }
    </style>

    <script>
        function q1() {
            fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
                //console.log(data)
                let row = data['RealtimeCityAir']['row']
                row.forEach((a) => {
                    console.log(a)
                })
            })
        }
    </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>

브라우저에서 버튼을 눌러서 데이터를 호출해 보면 값이 잘 들어오는 걸 확인할 수 있다.

들어온 json 데이터에서 키값으로 구이름과 미세먼지 값을 받아서 출력해 본다.

    <script>
        function q1() {
            fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
                //console.log(data)
                let row = data['RealtimeCityAir']['row']
                row.forEach((a) => {
                    let gu_name = a['MSRSTE_NM']
                    let gu_mise = a['IDEX_MVL']
                    console.log(gu_name,gu_mise )
                })
            })
        }
    </script>

 

브라우저에 그리기

가져온 데이터로 브라우저에 요소를 생성해 본다.

    <script>
        function q1() {
            fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
                let row = data['RealtimeCityAir']['row']
                $('#names-q1').empty()
                row.forEach((a) => {
                    let gu_name = a['MSRSTE_NM']
                    let gu_mise = a['IDEX_MVL']
                    let temp_html = `<li>${gu_name} : ${gu_mise}</li>`
                    $('#names-q1').append(temp_html)
                })
            })
        }
    </script>

반복문으로 리스트를 순회하면서 키로 값을 가져와서 li 요소를 생성하고 값을 넣는다.

반복문이 시작되기 전 기존의 내용을 지워주도록 한다.

 

 

이제 미세먼지 값이 40이 넘어가는 요소들은 붉은색으로 변경해 본다.

    <script>
        function q1() {
            fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
                //console.log(data)
                let row = data['RealtimeCityAir']['row']
                $('#names-q1').empty()
                row.forEach((a) => {
                    let gu_name = a['MSRSTE_NM']
                    let gu_mise = a['IDEX_MVL']
                    //console.log(gu_name,gu_mise )
                    //let temp_html = `<li>중구 : 82</li>`
                    let temp_html = ``;
                    if (gu_mise > 40)
                    {
                        temp_html = `<li class="bad">${gu_name} : ${gu_mise}</li>`
                    }
                    else{
                        temp_html = `<li>${gu_name} : ${gu_mise}</li>`
                    }
                    $('#names-q1').append(temp_html)
                })
            })
        }
    </script>

반복문 안에서 조건문을 통해서 temp_html 값을 분기해서 넣어준다.