개발과 계발/웹 개발

Ajax 연습하기

멈 무 2022. 11. 27. 19:12

 

서울시 미세먼지 API

 

크롬 Jason확장프로그램 깔고 보면 요러케 생김

Jason: 리스트, 딕셔너리가 섞여있는 형태   정도로 이해하면됨

 

 

 

    <script>
        $.ajax({
            type: "GET",
            url: "http://spartacodingclub.shop/sparta_api/seoulair",
            data: {},
            success: function (response) {
                console.log(response)
            }
        })

GET방식으로 이 url을 이용해서 console에 response를찍어주겠다

콘솔을 확인해보면

위 코드 넣었을 때 콘솔창 - row들 찍혀있음

 

    <script>
        $.ajax({
            type: "GET",
            url: "http://spartacodingclub.shop/sparta_api/seoulair",
            data: {},
            success: function (response) {
                let rows = response['RealtimeCityAir']['row'] 
                for (let i =0; i < rows.length; i++) {
                    let gu_name = rows[i]['MSRTE_NM']
                    let gu_mise = rows[i]['IDEX=NM']
                    console.log(gu_name, gu_mise)
                }     

                console.log(response['RealtimeCityAir']['row'])
            }
        })

다시

rows를  'RealTimeCityAir' 와 'row'만 response하도록 선언 해준 다음

25개 리스트를 반복해서 돌기  ---> for 반복문 이용

 

gu_name은 rows의 i번째의 MSRTE_NM

gu_mise 는 rows의 i번째의 IDEX=NM

 

그걸 다시 콘솔에서 로그를 보면

'무슨 구' '미세먼지 값' 이 쭈루루룩 나오는데

ㅡㅡ 아무것도 안나옴....

왜그런지 확인할 것....

왜안되나 했더니 ㅋㅋㅋㅋㅋ 녹화할때랑 API구성이 달라졌는지...

  • "ARPLT_MAIN": "O3",
  • "CO": 0.4,
  • "IDEX_MVL": 31,
  • "IDEX_NM": "좋음",
  • "MSRDT": "201912052100",
  • "MSRRGN_NM": "도심권",
  • "MSRSTE_NM": "중구",
  • "NO2": 0.015,
  • "O3": 0.018,
  • "PM10": 22,
  • "PM25": 14,
  • "SO2": 0.002

긁어오지를 못해서 그랬던것..ㅎ

 

 

 

<연습문제 1>

서울시 미세먼지 데이터 긁어와서  120보다 작으면 검정글씨, 크면 빨간글씨

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

<head>
    <meta charset="UTF-8">
    <title>jQuery 연습하고 가기!</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;
        }

        .bad{
            color: red;
        }
    </style>

    <script>
        function q1() {
            $('#names-q1').empty()
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/seoulair",
                data: {},
                success: function (response) {
                    let rows = response['RealtimeCityAir']['row']
                    for (let i = 0; i < rows.length; i++) {
                        let gu_name = rows[i]['MSRSTE_NM']
                        let gu_mise = rows[i]['IDEX_MVL']

                        let temp_html = ``

                        if (gu_mise > 120) {
                            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>

</head>

<body>
    <h1>jQuery+Ajax의 조합을 연습하자!</h1>

    <hr />

    <div class="question-box">
        <h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
        <p>모든 구의 미세먼지를 표기해주세요</p>
        <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
        <button onclick="q1()">업데이트</button>
        <ul id="names-q1">
        </ul>
    </div>
</body>

</html>

오늘은 미세먼지 상태가 좋아서 다 까만글씨다 ㅎ

 

 

 

<연습문제2>

서울시 따릉이 데이터 긁어와서

자전거 수가 5개 보다 작을 때 빨간글씨로 표시

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

<head>
    <meta charset="UTF-8">
    <title>JQuery 연습하고 가기!</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;
        }

        .urgent {
            color : red;
        }
    </style>

    <script>
        function q1() {
            $('#names-q1').empty()
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/seoulbike",
                data: {},
                success: function (response) {
                    let rows = response['getStationList']['row']
                    for (let i = 0; i < rows.length; i++) {
                        let name = rows[i]['stationName']
                        let rack = rows[i]['rackTotCnt']
                        let bike = rows[i]['parkingBikeTotCnt']

                        let temp_html = ``
                        
                        if (bike < 5) {
                            temp_html = `<tr class = "urgent">
                                            <td>${name}</td>
                                            <td>${rack}</td>
                                            <td>${bike}</td>
                                        </tr>`
                        } else {
                            temp_html = `<tr>
                                            <td>${name}</td>
                                            <td>${rack}</td>
                                            <td>${bike}</td>
                                        </tr>`
                        }
                        $('#names-q1').append(temp_html)

                    }
                }
            }
            )            // 여기에 코드를 입력하세요
        }
    </script>

</head>

<body>
    <h1>jQuery + Ajax의 조합을 연습하자!</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>
            </tbody>
        </table>
    </div>
</body>

</html>

완성본

 

<연습문제3>

르탄이API이용해서 버튼 누르면 이미지, 텍스트 바뀌게

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="UTF-8">
    <title>JQuery 연습하고 가기!</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;
      }
      div.question-box > div {
        margin-top: 30px;
      }
      
    </style>

    <script>
      function q1() {
        $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/rtan",
                data: {},
                success: function (response){
                    let url = response['url']
                    let msg = response['msg']

                    $('#img-rtan').attr('src', url)
                    $('test-rtan').text(msg)
                }
                }
            )            //
        // 여기에 코드를 입력하세요
      }
    </script>

  </head>
  <body>
    <h1>JQuery+Ajax의 조합을 연습하자!</h1>

    <hr/>

    <div class="question-box">
      <h2>3. 르탄이 API를 이용하기!</h2>
      <p>아래를 르탄이 사진으로 바꿔주세요</p>
      <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
      <button onclick="q1()">르탄이 나와</button>
      <div>
        <img id="img-rtan" width="300" src="http://spartacodingclub.shop/static/images/rtans/SpartaIcon11.png"/>
        <h1 id="text-rtan">나는 ㅇㅇㅇ하는 르탄이!</h1>
      </div>
    </div>
  </body>
</html>

 

버튼누르면 르탄이 이미지 바뀜