스파르타코딩클럽 2주차 개발일지

Hanal·2021년 9월 26일
0

01. 2주차 배울 것: jQuery, Ajax

jQuery를 이용해 Javascript로 HTML을 쉽게 제어.
Ajex를 이용해 다시 서버에 데이터를 요청.

02. Javascript 복습

  • 짝/홀수 판단하는 방법
let even = 4;
console.log(even % 2); // 2로 나눈 나머지가 0입니다.
let odd = 5;
console.log(odd % 2); // 2로 나눈 나머지가 1입니다.

console.log() 뜻: "console.log()"는 어떤 문자열을 출력하는 방법입니다. 그리고 그 대상은 브라우저에 탑재되어 있는 "개발자 도구"의 "콘솔"이라 불리는 화면입니다. "콘솔"에 표시하고 싶은 내용을 출력하여 프로그램이 제대로 작동하고 있는지 등을 확인할 수 있습니다.

  • 짝/홀수 onclick 함수
 <script>
        let count = 1;
        function hey() {
            if (count % 2 == 0) {
                alert('짝짝짝👏');
            } else {
                alert('홀홀홀🎅');
            }
						count += 1;
        }
    </script>

03.JQuery 시작하기

1)JQuery란?

  • HTML의 요소들을 조작하는, 편리한 Javascript를 미리 작성해둔 것. 라이브러리!

  • JQuery vs Javascript
    JQuery는 Javascript와 다른 특별한 소프트웨어가 아니라 미리 작성된 Javascript 코드. 전문 개발자들이 짜둔 코드를 잘 가져와서 사용하는 것.
    (그렇기 때문에, 쓰기 전에 "임포트"를 해야함.)

    Javascript로 길고 복잡하게 써야하는 것을

   document.getElementById("element").style.display = "none";

JQuery로 보다 직관적으로 쓸 수 있다.

   $('#element').hide();

04.JQuery 다뤄보기

1) JQuery 사용하기

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  • JQuery를 사용하는 방법
    css와 마찬가지로, jQuery를 쓸 때에도 "가리켜야" → 조작할 수 있습니다.
    예) 특정 인풋박스의 값을 → 가져와줘!
    예) 특정 div를 → 안보이게 해줘!

    css에서는 선택자로 class를 썼지요?
    jQuery에서는 id 값을 통해 특정 버튼/인풋박스/div/.. 등을 가리키게 됩니다.

2) 자주쓰는 JQuery들 다뤄보기

  • 모든 JQuery를 외워야 하나?
    A. 절대 X!
  • input 박스의 값을 가져와보기
<div class="posting-box">
    <div class="form-group">
        <label for="exampleInputEmail1">아티클 URL</label>
        <input id="post-url" type="email" class="form-control" aria-describedby="emailHelp"
            placeholder="">
    </div>
    <div class="form-group">
        <label for="exampleInputPassword1">간단 코멘트</label>
        <input type="password" class="form-control" placeholder="">
    </div>
    <button type="submit" class="btn btn-primary">기사 저장</button>
</div>
// 크롬 개발자도구 콘솔창에서 쳐보기
// id 값이 post-url인 곳을 가리키고, val()로 값을 가져온다.
$('#post-url').val();
  • div 보이기/숨기기
<div class="posting-box" id="post-box">
    <div class="form-group">
        <label for="exampleInputEmail1">아티클 URL</label>
        <input id="post-url" type="email" class="form-control" aria-describedby="emailHelp"
            placeholder="">
    </div>
    <div class="form-group">
        <label for="exampleInputPassword1">간단 코멘트</label>
        <input type="password" class="form-control" placeholder="">
    </div>
    <button type="submit" class="btn btn-primary">기사 저장</button>
</div>
// 크롬 개발자도구 콘솔창에 쳐보기
// id 값이 post-box인 곳을 가리키고, hide()로 안보이게 한다.(=css의 display 값을 none으로 바꾼다)
$('#post-box').hide();

// show()로 보이게 한다.(=css의 display 값을 block으로 바꾼다)
$('#post-box').show();
  • css의 값 가져와보기 (수업에선 display 속성 값을 가져옴)
$('#post-box').hide();
$('#post-box').css('display');

$('#post-box').show();
$('#post-box').css('display');
  • 태그 내 텍스트 입력하기
    (1) input box의 경우
$('#post-url').val('여기에 텍스트를 입력하면!');

(2)다른 것들- 예)버튼의 텍스트 바꾸기

// 가리키고 싶은 버튼에 id 값을 준다음
<button id="btn-posting-box" type="button" class="btn btn-primary">포스팅 박스 열기</button>
$('#btn-posting-box').text('포스팅 박스 닫기');
  • 태그 내 html html입력하기
    --<디브>~</디브>내에, 동적으로 html을 넣고 싶을 땐?
    예) 포스팅되면 -> 카드 추가
    // 사이에 html을 넣고 싶은 태그에 id값을 준 다음
    <div id="cards-box" class="card-columns">
       <div class="card">
         <img class="card-img-top" src="https://www.fodors.com/wp-content/uploads/2018/10/4_UltimateRome_PiazzaNavona-975x650.jpg" alt="Card image cap">
         <div class="card-body">
           <a href="https://naver.com/" class="card-title">여기 기사 제목이 들어가죠</a>
           <p class="card-text">여기에 기사 내용이 들어가겠죠</p>
           <p class="card-text comment">여기엔 코멘트가 들어갑니다</p>
         </div>
       </div>
     </div>
 (1) 버튼을 넣어보기

let temp_html = <button>나는 추가될 버튼이다!</button>;
//여기서 백틱(`)으로 감싼 temp_html은 문자열인 상태다.
$('#cards-box').append(temp_html);
//이 HTML처럼 생긴 문자열을 HTML로 변환시켜준다.

$(target).append(source)
//append() 메소드는 선택된 요소의 마지막에 새로운 HTML 요소나 콘텐츠를 추가한다.

(2) 버튼 말고, 카드를 넣어보기

// 주의: 홑따옴표(')가 아닌 backtick()으로 감싸야 합니다. // 숫자 1번 키 왼쪽의 버튼을 누르면 backtick()이 입력됩니다.
// backtick을 사용하면 문자 중간에 Javascript 변수를 삽입할 수 있습니다.
let img_url = 'https://www.eurail.com/content/dam/images/eurail/Italy%20OCP%20Promo%20Block.adaptive.767.1535627244182.jpg';
let link_url = 'https://naver.com/';
let title = '여기 기사 제목이 들어가죠';
let desc = '기사의 요약 내용이 들어갑니다. 동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라만세 무궁화 삼천리 화려강산...';
let comment = '여기에 코멘트가 들어갑니다.';

let temp_html = `


                <div class="card-body">
                    <a href="${link_url}" class="card-title">${title}</a>
                    <p class="card-text">${desc}</p>
                    <p class="card-text comment">${comment}</p>
                </div>
            </div>`;

$('#cards-box').append(temp_html);


5. JQuery 적용하기(나홀로메모장)
6.
7. 서버-클라이언트 통신 이해하기
- 클라이언트 -> 서버: GET요청 이해하기

API는 은행 창구와 같은 것!

같은 예금 창구에서도 개인 고객이냐 기업 고객이냐에 따라
가져와야 하는 것 / 처리해주는 것이 다른 것처럼,

클라이언트가 요청 할 때에도, "타입"이라는 것이 존재합니다.

* GET  → 통상적으로! 데이터 조회(Read)를 요청할 때
         예) 영화 목록 조회

* POST → 통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때.
          예) 회원가입, 회원탈퇴, 비밀번호 수정

이 중에서 오늘은 GET 방식에 대해 배워보겠습니다. (POST는 4주차에 배웁니다)


- GET 방식으로 데이터를 전달하는 방법

?  : 여기서부터 전달할 데이터가 작성된다는 의미입니다.
& : 전달할 데이터가 더 있다는 뜻입니다.

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

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


- 여기서 잠깐, 그럼 code라는 이름으로 영화번호를 주자!는 것은
누가 정하는 것일까요?

→ 네, 바로 프론트엔드 개발자와 백엔드 개발자가 미리 정해둔 약속입니다.

프론트엔드: "code라는 이름으로 영화번호를 주면 될까요?"
백엔드: "네 그렇게 하시죠. 그럼 code로 영화번호가 들어온다고 생각하고 코딩하고 있을게요"

8. Ajax 시작하기
(1) Ajax 시작하기
- 참고: Ajax는 jQuery를 임포트한 페이지에서만 동작 가능.

- Ajax 코드 해설

$.ajax({
type: "GET", // GET 방식으로 요청한다.
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
}
})


- $ajax 코드 설명
-- type:"GET" -> GET 방식으로 요청한다.
-- url: 요청할 url
-- data: 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요.)

리마인드
GET 요청은, url뒤에 아래와 같이 붙여서 데이터를 가져갑니다.
http://naver.com?param=value&param2=value2 

POST 요청은, data : {} 에 넣어서 데이터를 가져갑니다.
data: { param: 'value', param2: 'value2' },

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

success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
console.log(response)
}


(2) Ajax 통신의 결과값을 이용해보기

$.ajax({
type: "GET",
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
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://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
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);
}
}
});

9. Ajax 함께 연습하기
- Ajax 연습
jQuery 연습하고 가기!
<!-- 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>

jQuery+Ajax의 조합을 연습하자!

<hr />

<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>
``` - Ajax 연습(완성) ``` jQuery 연습하고 가기!
<!-- 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>

jQuery+Ajax의 조합을 연습하자!

<hr />

<div class="question-box">
    <h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
    <p>모든 구의 미세먼지를 표기해주세요</p>
    <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
    <button onclick="q1()">업데이트</button>
    <ul id="names-q1">
    </ul>
</div>
``` -[한 걸음 더] 미세먼지 수치가 70이상이 곳 빨갛게 보여주기. 완성본 ``` jQuery 연습하고 가기!
<!-- 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;
    }
</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 = ''

                    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>

jQuery+Ajax의 조합을 연습하자!

<hr />

<div class="question-box">
    <h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
    <p>모든 구의 미세먼지를 표기해주세요</p>
    <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
    <button onclick="q1()">업데이트</button>
    <ul id="names-q1">
    </ul>
</div>
```
  1. Ajax 연습하기(2)
  • 랜덤 고양이 사진 API 이용하기
  • 고양이 OpenAPI
    링크텍스트
  • 힌트: "jQuery 이미지태그 src 바꾸기" 라고 구글에 검색해보세요!

-퀴즈

<!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() {
        // 여기에 코드를 입력하세요
      }
    </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" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"/>
      </div>
    </div>
  </body>
</html>
  • 완성
<!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>
profile
My goal is to become a developer. I will upload what I learned on a weekly basis.

0개의 댓글