2023.01.06 개발일지 - Fetch 퀴즈

클로이🖤·2023년 1월 6일
0

Web-developer

목록 보기
11/22
post-thumbnail

JQuery+Ajax의 조합 연습

이번 일지에서는 서울시 실시간 따릉이 현황을 이용해서 모든 위치의 따릉이 현황을 보여주는 페이지를 만들어 볼 예정.

서울시 실시간 따릉이 현황을 열어보면

getStationList: {
row: [
{
parkingBikeTotCnt: 13,
rackTotCnt: 20,
shared: 7,
stationName: "301. 경복궁역 7번출구 앞"
},
{
parkingBikeTotCnt: 3,
rackTotCnt: 22,
shared: 19,
stationName: "302. 경복궁역 4번출구 뒤"
},
}

이런 식으로 parkingBikeTotCnt에서 몇 대가 주차되어 있는지, rackTotCnt에서 총 주차될 수 있는 수, stationName = 거치대 위치라고 볼 수 있다. 이것들을 사용해서 코드를 작성해 볼 것. 일단 뼈대를 불러와 준다.

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

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

    <script>
        function q1() {
            // 여기에 코드를 입력하세요

                    }
    </script>

</head>

<body>
    <h1>Fetch 연습하자!</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>
                    <td>102. 망원역 1번출구 앞</td>
                    <td>22</td>
                    <td>0</td>
                </tr>
                <tr>
                    <td>103. 망원역 2번출구 앞</td>
                    <td>16</td>
                    <td>0</td>
                </tr>
                <tr>
                    <td>104. 합정역 1번출구 앞</td>
                    <td>16</td>
                    <td>0</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>

</html>

이번에도 q1 함수에 fetch 코드를 작성해서 미세먼지때 처럼 만들어 주면 될듯 ! 다른 건 나중에 건드리고 지금은 function q1만 수정.

      function q1() {
        fetch("http://spartacodingclub.shop/sparta_api/seoulbike")
          .then((res) => res.json())
          .then((data) => {
            let rows = data["getStationList"]["row"];

            rows.forEach((seoulBike) => {
              console.log(seoulBike);
            });
          });
      }

일단 따릉이 url 넣어주고, rows라는 변수에 getstationList 리스트 내에 row 까지 설정해줌. 그리고 rows에 forEach문 넣어서 console 창에 row가 한줄씩 나오도록 해봤다. 결과는 성공 ~ !

이렇게 하나씩 잘 출력되는 모습을 볼 수 있다. 이제 이걸 html에 append 하는 것까지 해보자.
일단 html에 붙여넣기 전에 거치대 위치, 거치대 수, 현재 거치된 따릉이 수에 들어갈 변수를 각각 location, rack, parking으로 작성했다. 이걸 콘솔창에 출력하는 것까지 해본 결과,

      function q1() {
        fetch("http://spartacodingclub.shop/sparta_api/seoulbike")
          .then((res) => res.json())
          .then((data) => {
            let rows = data["getStationList"]["row"];

            $("#names-q1").empty();
            rows.forEach((seoulBike) => {
              let location = seoulBike["stationName"];
              let rack = seoulBike["rackTotCnt"];
              let parking = seoulBike["parkingBikeTotCnt"];
              console.log(location, rack, parking);
            });
          });
      }


이렇게 내가 원하는 정보만 딱 나오는 것을 확인할 수 있다. 이걸 이제 붙여넣으면 완성?

      function q1() {
        fetch("http://spartacodingclub.shop/sparta_api/seoulbike")
          .then((res) => res.json())
          .then((data) => {
            let rows = data["getStationList"]["row"];

            $("#names-q1").empty();
            rows.forEach((seoulBike) => {
              let location = seoulBike["stationName"];
              let rack = seoulBike["rackTotCnt"];
              let parking = seoulBike["parkingBikeTotCnt"];
              
              let temp_html = `<tr>
                                  <td>${location}</td>
                                  <td>${rack}</td>
                                  <td>${parking}</td>
                               </tr>`;
              $('#names-q1').append(temp_html);
            });
          });
      }

temp_html 변수 작성하고, 테이블 형태로 작성이 되어있기 때문에 tr-td를 다 가져와야 함. td에 작성해놓은 변수 맞춰서 순서대로 넣어주고, names-q1부분에 작성해둔 temp_html을 append하면 끝 ! ( 지우고 붙이라고 했으니까 empty는 필수 ~ !! ) 근데 조금 더 가서 저번처럼 어떤 특정한 수 미만인 곳을 빨간색으로 표시하려면 ,, ? ( 따릉이 대수가 5대 미만인 곳을 빨간색으로 만들어주자 ! )

First. css를 먼저 만들어 줬다. 색상을 빨간색으로 하고 폰트가 두껍게 출력되도록 설정했다.

      .less {
        color: rgb(255, 0, 0);
        font-weight: bold;
      }
      table { //table 내의 text가 가운데로 정렬되어있는 게 보기 좋을 것 같아서 조금 수정했다.
        text-align: center;
        border: 1px solid;
        border-collapse: collapse;
      }

Second. 반복문 작성. 일단 temp_html을 빈 백틱으로 설정해 주고, if문을 작성했다. parking이 5보다 작거나 같으면 less라는 클래스가 지정된 temp_html이 복사되게, else면 class 지정되어있지 않은 temp_html이 들어가도록 만들었다. 이걸 append 하면 끝 ! 완성된 코드는 아래와 같다.

      function q1() {
        fetch("http://spartacodingclub.shop/sparta_api/seoulbike")
          .then((res) => res.json())
          .then((data) => {
            let rows = data["getStationList"]["row"];

            $("#names-q1").empty();
            rows.forEach((seoulBike) => {
              let location = seoulBike["stationName"];
              let rack = seoulBike["rackTotCnt"];
              let parking = seoulBike["parkingBikeTotCnt"];

              let temp_html = ``;
              if (parking <= 5) {
                temp_html = `<tr class = "less">
                                  <td>${location}</td>
                                  <td>${rack}</td>
                                  <td>${parking}</td>
                               </tr>`;
              } else {
                temp_html = `<tr>
                                  <td>${location}</td>
                                  <td>${rack}</td>
                                  <td>${parking}</td>
                               </tr>`;
              }
              $("#names-q1").append(temp_html);
            });
          });
      }

여기까지 2주차 공부 끝 ! 아래는 따릉이 위치 나타내는 코드

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <title>Fetch 연습하고 가기!</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 {
        text-align: center;
        border: 1px solid;
        border-collapse: collapse;
      }

      td,
      th {
        padding: 10px;
        border: 1px solid;
      }
      .less {
        color: rgb(255, 0, 0);
        font-weight: bold;
      }
    </style>

    <script>
      function q1() {
        fetch("http://spartacodingclub.shop/sparta_api/seoulbike")
          .then((res) => res.json())
          .then((data) => {
            let rows = data["getStationList"]["row"];

            $("#names-q1").empty();
            rows.forEach((seoulBike) => {
              let location = seoulBike["stationName"];
              let rack = seoulBike["rackTotCnt"];
              let parking = seoulBike["parkingBikeTotCnt"];

              let temp_html = ``;
              if (parking <= 5) {
                temp_html = `<tr class = "less">
                                  <td>${location}</td>
                                  <td>${rack}</td>
                                  <td>${parking}</td>
                               </tr>`;
              } else {
                temp_html = `<tr>
                                  <td>${location}</td>
                                  <td>${rack}</td>
                                  <td>${parking}</td>
                               </tr>`;
              }
              $("#names-q1").append(temp_html);
            });
          });
      }
    </script>
  </head>

  <body>
    <h1>Fetch 연습하자!</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>
            <td>102. 망원역 1번출구 앞</td>
            <td>22</td>
            <td>0</td>
          </tr>
          <tr>
            <td>103. 망원역 2번출구 앞</td>
            <td>16</td>
            <td>0</td>
          </tr>
          <tr>
            <td>104. 합정역 1번출구 앞</td>
            <td>16</td>
            <td>0</td>
          </tr>
        </tbody>
      </table>
    </div>
  </body>
</html>
profile
front-end developer

0개의 댓글