웹개발 종합반 2주차_8일

ddabong-dochi·2022년 4월 25일
0
post-thumbnail

1. Ajax 코드 해설

$.ajax({
  type: "GET", // GET 방식으로 요청한다.
  url: "http://spartacodingclub.shop/sparta_api/seoulair",
  data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
  success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
    console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
  }
})
  • type: "GET" 방식으로 요청한다.
  • url: 요청할 url
  • data: 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두기)

    GET 요청은, url뒤에 아래와 같이 붙여서 데이터를 가져갑니다.
    http://naver.com?param=value¶m2=value2
    POST 요청은, data : {} 에 넣어서 데이터를 가져갑니다.
    data: { param: 'value', param2: 'value2' },

  • success: 성공하면 response 값에 서버의 결과 값을 담아서 함수 실행

🔥모든 구의 미세먼지 값을 찍어보기

  • 미세먼지 데이터가 어디에 있는지 찾기. 특히, key, value 구분하기
$.ajax({
  type: "GET",
  url: "http://spartacodingclub.shop/sparta_api/seoulair",
  data: {},
  success: function (response) {
    let mise_list = response["RealtimeCityAir"]["row"];
    for (let i = 0; i < mise_list.length; i++) {
      let mise = mise_list[i];
      let gu_name = mise["MSRSTE_NM"];
      let gu_mise = mise["IDEX_MVL"];
      console.log(gu_name, gu_mise);
    }
  }
});

2. 서울시 미세먼지 수치가 70이상인 곳을 빨갛게 보여줘!

<!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;
            font-weight: bold;
        }
    </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 > 70) {
                            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>
profile
비전공자 직장인 개발일지😆

0개의 댓글