ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 21.09.11~14. 2-7~12강 (JSON, Ajax)
    일기 2021. 9. 12. 00:04

    [JSON]

    클라이언트: 나한테 줄 데이터 없니?

    서버: 여기 있어! 가져가!

     

    그리고 클라이언트 손에 쥐어지는 JSON 포맷 위의 데이터

     

    JSON: 서버가 클라이언트에게 데이터를 줄 때 내려주는 포맷

     

     

     

    [API 중 GET]

    ? 붙여서 데이터를 가져간다!

     

     

     

    [Ajax]

    jQuery 임포트 되어야 사용 가능

     

     

     

     

    *기본골격

     

    $.ajax({
      type: "GET",
      url: "여기에URL을입력",
      data: {},
      success: function(response){
        console.log(response)
      }
    })

     

     

     

     

     

    $.ajax({
      type: "GET",
      url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
      data: {},
      success: function(response){         =>값들이 response로 들어와서 console에 찍힘
        console.log(response)
      }
    })


    {readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
    VM35:6

    {RealtimeCityAir: {…}}

     

     

     

     

    $.ajax({
      type: "GET",
      url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
      data: {},       =>post에서만 사용하는 항목. get에서는 안씀
      success: function(response){
        console.log(response['RealtimeCityAir']['row'][0])
      }
    })
    {readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
    VM80:6 {MSRDT: '202109131000', MSRRGN_NM: '도심권', MSRSTE_NM: '중구', PM10: 24, PM25: 15, …}

     

     

     

     

    $.ajax({
      type: "GET",
      url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
      data: {},
      success: function(response){
        let rows = response['RealtimeCityAir']['row']
        for (let i = 0; i < rows.length; i++) {     

    =>반복문! i가 0부터 rows의 length(딕셔너리 개수)가 될 때까지 i가 하나씩 늘어난다.
            let gu_name = rows[i]['MSRSTE_NM']
            let gu_mise = rows[i]['IDEX_MVL']
            if (gu_mise < 40) {

            console.log(gu_name,gu_mise)
            }
        }

      }
    })
    {readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
    VM519:12 서대문구 36
    VM519:12 강남구 -99

     

     

     

     

     

     

    [연습하기]

     

    <!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()=>새로고침하는 jQuery
     $.ajax({
       type: "GET",
       url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
       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 > 60) {
                temp_html = `<li class="bad">${gu_name} : ${gu_mise}</li>`
             } else {
                temp_html = `<li>${gu_name} : ${gu_mise}</li>`
             }

             $('#names-q1').append(temp_html)  =>만들어둔 temp_html을 '#...'에 붙인다(append)
             }
         }
     })
    }
    </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">
    <li>중구 : 82</li>
    <li>종로구 : 87</li>
    <li>용산구 : 84</li>
    <li>은평구 : 82</li>
    </ul>
    </div>
    </body>

    </html>

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    [퀴즈1]

     

    *답

     

    <!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;
    }

    .lack {
    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 where = rows[i]['stationName']
    let rack = rows[i]['rackTotCnt']
    let bike = rows[i]['parkingBikeTotCnt']

    let temp_html = ``
    if (bike < 5) {
    temp_html = `<tr class="lack">
    <td>${where}</td>
    <td>${rack}</td>
    <td>${bike}</td>
    </tr>`
    } else {
    temp_html = `<tr>
    <td>${where}</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">
    </tbody>
    </table>
    </div>
    </body>

    </html>

     

     

     

     

     

    [퀴즈2]

     

    *참고

     

    <img id="img_form_url">

     

    위 img 의 src를 변경하는 방법

    $("#img_form_url").attr("src", imgurl);



    *답

     

    <!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: "https://api.thecatapi.com/v1/images/search",
    data: {},
    success: function (response) {
    let imgurl = response[0]['url']    =>리스트의 0번째의 url 값을 불러온다.
    $("#img-cat").attr("src", imgurl);  =>img의 src를 변경하는 jquery (#img id)
    }
    })
    }
    </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-cat" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"/>
    </div>
    </div>
    </body>
    </html>

     

     

     

     

     

     

     

    [숙제]

     

    *참고 (로딩 후 호출하기)

     

    $(document).ready(function(){
    alert('다 로딩됐다!')
    });

     

     

Designed by Tistory.