공부하자/웹개발일지

[웹개발일지] #4. Ajax 적용

snbrin 2022. 3. 5. 15:36

 

 

풀스택 웹개발 공부 기록하기 #4.

 

😉 jQuery를 이용해 Javascript로 HTML을 제어했다면,

Ajax를 이용해 다시 서버에 데이터를 요청하고 받아오기😉

 


 

 

💾 Ajax

Ajax는 jQuery를 임포트한 페이지에서만 동작 가능!!

일반 구글 링크에서 개발자도구를 열면 jQuery가 임포트되어있지 않으므로 에러 발생

 

👉 ajax의 기본 뼈대

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

GET 요청은, url뒤에 아래와 같이 붙여서 데이터를 가져감

http://~~~?param=value¶m2=value2

POST 요청은, data:{ }에 넣어서 데이터를 가져감

data : { param : 'value', param2 : 'value2' },

 

 

💻미세먼지 OpenAPI 실습

실시간으로 업데이트되는 값 가져오기

 

여기서 상기해야할 것은?

👉  jQuery와 Ajax의 조합 방식

👉 뽑아낼 데이터 지정 방식

let gu_mise = rows[i]['INDEX_MVL'];

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

    <script>
        function q1() {
            // 여기에 코드를 입력하세요
            $('#names-q1').empty();
            $.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 = `<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>

 

 

💻서울시 따릉이 OpenAPI 실습

거치된 따릉이 수 &amp;lt; 5 이면 빨간색

 

여기서 상기해야할 것은?

👉 for문 안에 있는 코드

👉 뽑아낼 데이터 지정 방식

let rack_name = rows[i]['stationName'];

<!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;
            font-weight: bold;
        }
    </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 rack_name = rows[i]['stationName'];
                        let rack_cnt = rows[i]['rackTotCnt'];
                        let bike_cnt = rows[i]['parkingBikeTotCnt'];
                        let temp_html = '';
                        if (bike_cnt < 5) {
                            temp_html = `<tr class="urgent">
                                <td>${rack_name}</td>
                                <td>${rack_cnt}</td>
                                <td>${bike_cnt}</td>
                              </tr>`
                        } else {
                            temp_html = `<tr>
                                <td>${rack_name}</td>
                                <td>${rack_cnt}</td>
                                <td>${bike_cnt}</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>

 

💻랜덤 고양이 사진 OpenAPI 실습

여기서 상기해야할 것은?

👉 jQuery 이미지 태그

$("#img-cat").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'];
              $("#img-cat").attr("src", imgurl);
            }
          })
      }
    </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" width="300" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"/>
      </div>
    </div>
  </body>
</html>