스파르타 웹 개발 종합 - 2주차

heehe·2023년 1월 11일
0

Sparta-coding club

목록 보기
8/16
post-thumbnail

오늘 공부한 내용 📋


  • 스파르타 웹 개발 종합 - 2주차 진행 완료
  • 서버 → 클라이언트 : “JSON” 이해
    • RealtimeCityAir라는 키 값에 딕셔너리 형 value가 들어가있고,
      그 안에 row라는 키 값에는 리스트형 value가 들어가있음
- 클라이언트 → 서버 Get 요청 이해
- **API는 은행 창구와 같은 것!** 클라이언트가 요청 할 때에도, "타입"이라는 것이 존재
- GET        →    통상적으로! 데이터 조회(Read)를 요청할 때
                           예) 영화 목록 조회
    
    
    ```jsx
    https://movie.naver.com/movie/bi/mi/basic.nhn?code=161967
    
    위 주소는 크게 두 부분으로 쪼개집니다. 바로 "?"가 쪼개지는 지점인데요.
    "?" 기준으로 앞부분이 <서버 주소>, 뒷부분이 [영화 번호] 입니다.
    
    * 서버 주소: https://movie.naver.com/movie/bi/mi/basic.nhn
    * 영화 정보: code=161967
    
    **GET 방식으로 데이터를 전달하는 방법**
    
    ?  : 여기서부터 전달할 데이터가 작성된다는 의미입니다.
    & : 전달할 데이터가 더 있다는 뜻입니다.
    
    예시) google.com/search?q=아이폰&sourceid=chrome&ie=UTF-8
    
             위 주소는 google.com의 search 창구에 다음 정보를 전달합니다!
             q=아이폰                        (검색어)
             sourceid=chrome        (브라우저 정보)
             ie=UTF-8                      (인코딩 정보)
    
    **여기서 잠깐, 그럼 code라는 이름으로 영화번호를 주자!는 것은
    누가 정하는 것일까요?**
    
    → 네, 바로 프론트엔드 개발자와 백엔드 개발자가 미리 정해둔 **약속**입니다.
    
    프론트엔드: *"code라는 이름으로 영화번호를 주면 될까요?"*
    백엔드: *"네 그렇게 하시죠. 그럼 code로 영화번호가 들어온다고 생각하고 코딩하고 있을게요"*
    ```
    
- POST     →     통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때
                           예) 회원가입, 회원탈퇴, 비밀번호 수정
  • Ajax 시작하기
  • Ajax는 jQuery를 임포트한 페이지에서만 동작 가능
    --Ajax 기본 골격
    
    $.ajax({
      type: "GET", // GET 방식으로 요청한다.
      url: "http://spartacodingclub.shop/sparta_api/seoulair", --요청할 API url
      data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
      success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
        console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
      }
    })
    
    --$ajax 코드 설명
    리마인드
    GET 요청은, url뒤에 아래와 같이 붙여서 데이터를 가져갑니다.
    http://naver.com?param=value&param2=value2 
    
    POST 요청은, data : {} 에 넣어서 데이터를 가져갑니다.
    data: { param: 'value', param2: 'value2' },
    
  • 서울시 OpenAPI 이용하여 실시간 미세먼지 상태 확인
    <!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;
            } -- 미세먼저 수치 70 이상 글자 색상 스타일 지정
        </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>`
                            } -- 미세먼지 수치 70이상 지정
                            
                            $('#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>
  • 따릉이 Open 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;
            }
    
            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>
  • 랜덤 르탄이 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 imgurl = response['url'];
                  $("#img-rtan").attr("src", imgurl);
    
                  let msg = response['msg'];
                  $("#text-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>
  • 2주차 숙제 완료 / 숙제 해설 답안 코드 비교 확인
    • 날씨 API 이용하여 날씨 정보 넣기

      <script>
            $(document).ready(function () {
              alert('다 로딩됐다!')
            });
            $.ajax({
                      type: "GET",
                      url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
                      data: {},
                      success: function (response) {
                        let msg = response['temp'];
                        $("#temp").text(msg);
                      }
                  })
      
          </script>

회고 및 코멘트 🙏🏻


  • 제어문부터 연습만이 살길인거 같다.. 대충 문제로 전체 훑어보는 수준 ㅠ
  • 자바스크립트 부분이 어렵긴 했다. JQuray부터 Ajax까지. 그래도 연습 페이지를 계속 만들다 보니까 구조가 이해되었다.
  • 2주차 숙제도 마무리 완료!
profile
성장하고픈 ISFJ

0개의 댓글