스파르타코딩클럽 내일배움단 웹개발 종합반 -5

몽슈뜨·2022년 10월 21일
0

웹개발 종합반

목록 보기
5/11
post-thumbnail

✨홀짝 판별 onclick 함수 만들어보기

클라이언트→서버: GET 요청 이해하기

  • API는 은행 창구와 같은 것!

    • 같은 예금 창구에서도 개인 고객이냐 기업 고객이냐에 따라
      가져와야 하는 것 / 처리해주는 것이 다른 것처럼,
      클라이언트가 요청 할 때에도, "타입"이라는 것이 존재합니다.
    • GET → 통상적으로! 데이터 조회(Read)를 요청할 때
      예) 영화 목록 조회
    • POST → 통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때
      예) 회원가입, 회원탈퇴, 비밀번호 수정
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로 영화번호가 들어온다고 생각하고 코딩하고 있을게요"


✨Ajax 시작하기

Jsonview
미세먼지OpenAPI

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

    • type : "GET" → GET 방식으로 요청한다.
      url : 요청할 url
      data : 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)

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

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

      success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
       console.log(response) 
      }
  • Ajax 통신의 결과값을 이용해보기

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

    $.ajax({
     type: "GET",
     url: "http://spartacodingclub.shop/sparta_api/seoulair",
     data: {},
     success: function(response){
    		// 값 중 도봉구의 미세먼지 값만 가져와보기
    		let dobong = response["RealtimeCityAir"]["row"][11];
    		let gu_name = dobong['MSRSTE_NM'];
    		let gu_mise = dobong['IDEX_MVL'];
    		console.log(gu_name, gu_mise);
     }
    })
  • 모든 구의 미세먼지 값을 찍어보기

    $.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);
       }
     }
    });


    ✨Ajax 함께 연습하기

  • Ajax 기본 골격

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

  • Ajax 연습

    <!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() {
               // 여기에 코드를 입력하세요
           }
       </script>
    </head>
    <body>
      <h2>jQuery+Ajax의 조합을 연습하자!</h2>
    
       <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>
  • Ajax연습(완성)

  • Ajax 연습 (미세먼지 수치 70이상은 빨갛게 해보기)

     <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>

✨Quiz_Ajax 연습하기

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

이미지 바꾸기 : $("#아이디값").attr("src", 이미지URL);
텍스트 바꾸기 : $("#아이디값").text("바꾸고 싶은 텍스트");

  • Ajax퀴즈2 완성

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

  • 이렇게 만들면 완료!
  • 로딩 후 호출하기

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

    <script>
        $(document).ready(function () {
                $.ajax({
                    type: "GET",
                    url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
                    data: {},
                    success: function (response) {
                        let city = response['city']
                        let temp = response['temp']

                        $('#city').text(city)
                        $('#temp').text(temp)
                    }

                })
            }
        )
    </script>

</head>
<body>
<div class="mytitle">
    <h1>고양이 방명록</h1>
    <p>     <!--span을 각각 만들어 city,temp값을 출력했다 -->
        <span id="city"></span> : <span id="temp"></span></p>
</div>
  • 💻 출력
profile
개발자되면 맥북사줄께

0개의 댓글