크래프톤 정글

[크래프톤 정글 ] chapter 2 - javascript & jquery

하루이2222 2024. 7. 11. 06:01

01. JavaScript 소개

자바스크립트란?

  • JavaScript (JS): HTML 상에서 쓸 수 있는 프로그래밍 언어.
  • 브라우저에서 JavaScript만 알아듣는 이유: 역사적 이유와 이미 정립된 표준 때문. 모든 브라우저가 기본적으로 JavaScript를 지원하도록 설계됨.
  • Java와 JavaScript 차이: 전혀 다른 언어.

자바스크립트 맛보기

  1. 버튼 클릭 시 경고창 기능:

     <!doctype html>
     <html lang="en">
     <head>
         <meta charset="utf-8">
         <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
         <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" crossorigin="anonymous">
         <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" crossorigin="anonymous"></script>
         <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
         <title>JavaScript Example</title>
         <style>
             * { font-family: 'Jua', sans-serif; }
             .wrap { margin: auto; width: 900px; }
             .posting-box { margin: 10px auto 30px auto; width: 500px; border: 3px solid black; border-radius: 5px; padding: 25px; }
         </style>
     </head>
     <body>
         <div class="wrap">
             <div class="jumbotron">
                 <h1 class="display-4">나홀로 링크 메모장!</h1>
                 <p class="lead">중요한 링크를 저장해두고, 나중에 볼 수 있는 공간입니다</p>
                 <hr class="my-4">
                 <p class="lead">
                     <a class="btn btn-primary btn-lg" href="#" role="button">포스팅박스 열기</a>
                 </p>
             </div>
             <div class="posting-box">
                 <div class="form-group">
                     <label for="exampleInputEmail1">아티클 URL</label>
                     <input type="email" class="form-control" placeholder="">
                 </div>
                 <div class="form-group">
                     <label for="exampleInputPassword1">간단 코멘트</label>
                     <input type="password" class="form-control" placeholder="">
                 </div>
                 <button onclick="hey()" type="button" class="btn btn-primary">기사 저장</button>
             </div>
         </div>
         <script>
             function hey() { alert('안녕!'); }
         </script>
     </body>
     </html>
  2. 버튼 클릭 시 콘솔에 문구 출력:

     <button onclick="hello()" type="button" class="btn btn-primary">기사 저장</button>
     <script>
         function hello() { console.log('Hello!'); }
     </script>
  3. 콘솔창 직접 코드 작성:

     function bye() { console.log('Good-bye!'); }
     bye();

자바스크립트 기초 문법

  • 변수 선언:

      let num = 10;
      let word1 = "jungle";
  • 자료형과 기본 연산:

      let a = 7, b = 2;
      console.log(a + b, a - b, a * b, a / b, a % b);
      let word1 = "hello", word2 = "world";
      console.log(word1 + " " + word2);
  • 리스트와 딕셔너리:

      let arr = [1, 2, 3, "four"];
      let dict = {name: "John", age: 30};
      console.log(arr[2], dict["name"]);
  • 함수:

      function sum(a, b) { return a + b; }
      console.log(sum(3, 4));
  • 조건문:

      let x = 10;
      if (x > 5) { console.log("x is greater than 5"); }
      else { console.log("x is not greater than 5"); }
  • 반복문:

      for (let i = 0; i < 5; i++) { console.log(i); }

02. 자바스크립트 연습

Q1. 1부터 n까지의 합 구하기

function add_num(n) {
    let sum = 0;
    for (let i = 1; i <= n; i++) { sum += i; }
    return sum;
}
console.log(add_num(10)); // 55

Q2. 미세먼지 값이 40 미만인 구 이름과 값 출력

let mise_list = [...]; // 데이터
function show_good(n) {
    console.log("미세먼지 수치가 " + n + "보다 낮은 구의 목록");
    for (let i = 0; i < mise_list.length; i++) {
        let gu_name = mise_list[i]["MSRSTE_NM"];
        let gu_mise = mise_list[i]["IDEX_MVL"];
        if (gu_mise < n) { console.log(gu_name, gu_mise); }
    }
}
show_good(40);

Q3. 자전거가 5개 이하인 정류장 이름 출력

let bikes = [...]; // 데이터
function show_names(num) {
    for (let i = 0; i < bikes.length; i++) {
        if (bikes[i]['parkingBikeTotCnt'] <= num) {
            console.log(bikes[i]['stationName']);
        }
    }
}
show_names(5);

03. jQuery

jQuery 소개

  • jQuery: HTML 요소들을 조작하는 편리한 JavaScript 라이브러리.
  • 임포트: <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" crossorigin="anonymous"></script>

자주 쓰이는 jQuery 다뤄보기

  1. input 박스 값 가져오기:

     <input id="post-url" type="email" class="form-control" placeholder="">
     <script>
         let url = $('#post-url').val();
         console.log(url);
     </script>
  2. div 숨기기 / 보이기:

     <div class="posting-box" id="post-box">...</div>
     <script>
         $('#post-box').hide();
         $('#post-box').show();
     </script>
  3. 태그 내 텍스트 입력하기:

     <button id="btn-posting-box" type="button" class="btn btn-primary">포스팅박스 열기</button>
     <script>
         $('#btn-posting-box').text('포스팅박스 닫기');
     </script>
  4. 태그 내 html 입력하기:

     <div id="cards-box" class="card-columns">...</div>
     <script>
         let temp_html = `<button>추가 버튼</button>`;
         $('#cards-box').append(temp_html);
     </script>
  5. 페이지 로딩 완료 후 실행:

     <script>
         $(document).ready(function(){
             alert('페이지가 로딩되었습니다.');
         });
     </script>

포스팅박스 열기/닫기 기능 구현

  1. HTML 수정:

     <button id="posting-box-btn" onclick="openclose()" class="btn btn-primary btn-lg">포스팅박스 열기</button>
     <div class="posting-box" id="post-box">...</div>
  2. JavaScript:

     function openclose() {
         let status = $('#post-box').css('display');
         if (status == 'block') {
             $('#post-box').hide();
             $('#posting-box-btn').text('포스팅박스 열기');
         } else {
             $('#post-box').show();
             $('#posting-box-btn').text('포스팅박스 닫기');
         }
     }

04. 서버-클라이언트 통신

Web API와 JSON

  • Web API: 서버에 요청을 보내고 응답을 받기 위한 명세.
  • JSON: 데이터 전달을 위한 텍스트 형식.

GET 요청

  • 예시: https://movie.daum.net/moviedb/main?movieId=111292

GET 방식 데이터 전달

  • ?param=value&param2=value2

05. Ajax

Ajax란?

  • Ajax: 비동기적인 웹 애플리케이션 제작 기법.

Ajax 사용 예제

  1. 기본 골격:

     function sayHello() {
         $.ajax({
             type: "POST",
             url: "/test",
             data: { test_give: '테스트값' },
             success: function (response) { alert(response['msg']); }
         });
     }
  2. JavaScript fetch 사용:

     fetch('/test', {
         method: 'POST',
         headers: { 'Content-Type': 'application/json' },
         body: JSON.stringify({ test_give: '테스트값' })
     })
     .then(res => res.json())
     .then(response => { alert(response['msg']); });