코딩하는 털보

웹개발 종합반 WIL - 2W 본문

Boot Camp/항해 99

웹개발 종합반 WIL - 2W

이정인 2021. 8. 2. 17:35

JQuery

jQuery는 HTML 요소들을 쉽게 조작하기 위해서 사용하는 미리 작성된 Javascript 코드 라이브러리이다. 쓰기 전에 import 해야한다.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

css가 선택자로 class를 사용했듯이 jQuery는 id를 통해 특정 요소를 가리키게 된다.

몇가지 JQuery 예시

  • 숨기기

    $('#post-box').hide();
  • 보이기

    $('#post-box').show();
  • 인풋박스의 값 가져오기 / 변경하기

    $('#post-url').val();
    $('#post-url').val('새로운 값');
  • 인풋박스 외 다른 값 가져오기 / 변경하기

    $('#btn-posting-box').text();
    $('#btn-posting-box').text('포스팅 박스 닫기');
  • CSS 값 가져오기

    $('#post-box').css('display');
    none
    $('#post-box').css('width');
    700px
  • HTML 요소 추가하기

    // ``으로 묶어서 javascript에서 HTML을 입력할 수 있다.
    let temp_html = '<button>나는 버튼이다</button>';
    $('#cards-box').append(temp_html);

서버-클라이언트 통신 이해하기

  • JSON

    • 서버와 교환하는 데이터의 "형식"이다.
    • key-value 쌍으로 이루어져 있어서 딕셔너리와 매우 유사하다.
    • value는 딕셔너리 또는 리스트가 될 수 있다.
  • API

    • 클라이언트에서 서버에 요청할 때 "창구"
    • API의 타입
      • GET : 통상적으로 데이터 조회 요청을 받는다.
      • POST : 통상적으로 데이터의 생성, 변경, 삭제 요청을 받는다.
  • GET 방식으로 데이터를 전달하는 방법

사실 우리가 브라우저에서 주소를 입력하고 엔터를 치는 행위도 GET 요청이다.

주소의 '?'부터 클라이언트에서 서버로 전달할 데이터를 작성한다. (여러개일 경우 '&'로 구분한다.)

예시) google.com/search?q=아이폰&sourceid=chrome&ie=UTF-8

     위 주소는 google.com의 search 창구(API)에 다음 정보를 전달합니다!
     q=아이폰                        (검색어)
     sourceid=chrome        (브라우저 정보)
     ie=UTF-8                      (인코딩 정보) 

Ajax

자바스크립트로 페이지 전환없이 서버에서 값을 받아올 수 있는 방법이다. (Ajax는 jQuery를 임포트한 페이지에서만 동작한다.)

Ajax 다뤄보기

  • 서울시 OpenApi로 구별 미세먼지 상태 데이터 요청하기.
$.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'];

        //수치가 100 미만인 곳만 출력하기.
          if ( gu_mise < 100 ) {
            console.log(gu_name, gu_mise);
        }
    }
   }
})
  • 서울시 OpenApi로 따릉이 현황 요청하고 station 별 거치대 수 및 따릉이 수 보여주기
        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 stationName = rows[i]['stationName'];
                        let rackTotCnt = rows[i]['rackTotCnt'];
                        let parkingBikeTotCnt = rows[i]['parkingBikeTotCnt'];
                        let temp_html = ``;

                        //따릉이 수가 5개 미만인 정거장은 다른 css 사용
                        if ( parkingBikeTotCnt < 5 ) {
                            temp_html = `<tr class="lessthan5">
                    <td>${stationName}</td>
                    <td>${rackTotCnt}</td>
                    <td>${parkingBikeTotCnt}</td>
                </tr>`;
                        } else {
                            temp_html = `<tr>
                    <td>${stationName}</td>
                    <td>${rackTotCnt}</td>
                    <td>${parkingBikeTotCnt}</td>
                </tr>`;
                        }

                        $('#names-q1').append(temp_html);
                    }
                }
            })
        }
  • 랜덤 고양이 사진 Api에서 고양이 사진 요청하고 보여주기
      function q1() {
        $.ajax({
          type: "GET",
          url: "https://api.thecatapi.com/v1/images/search",
          data: {},
          success: function (response) {
            let img_url = response[0]['url'];

            //attr() 메소드로 속성을 바꿀 수 있다.
            $('#img-cat').attr("src", img_url);
          }
        })
      }

2주차 숙제 (실시간 환률 가져오기)

  • 페이지를 로딩하고난 뒤 동작하도록 구현하기
        $(document).ready(function(){
          alert('다 로딩됐다!')
        });
  • 페이지를 로딩하고난 뒤 바로 환률을 가져와서 입력
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/rate",
                data: {},
                success: function (response) {
                    let rate = response['rate'];
                    let temp_txt = `달러-원 환율:${rate}`
                    $('#exchange_rate').append(temp_txt);
                }
            })
        });

Comments