자바스크립트 정리(3)

조이연·2023년 1월 4일
0

JSP

목록 보기
5/19

<CDN(Content Delivery Network)이란?>

CDN의 장점 : 내 프로젝트에 jQuery를 그냥 포함하면 사용자가 나한테서 파일을 받아간다
요즘 클라우드 서비스를 이용해 서버를 빌린다(AWS, MS Azure) -> 시간, 처리량, 입출량에 따라 요금 책정

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <title>Document</title>
    <script>
        const carts=[
            {no:122, name:'신라면', price:4100, count:1, total:4100},
            {no:357, name:'페레로로쉐 5T', price:3500, count:1, total:3500},
            {no:1113, name:'오레오', price:1200, count:1, total:1200}
        ];
        $(document).ready(function() {
            $.each(carts, function(i, c) {
                const template = `
                    <tr>
                        <td>${c.name}</td>
                        <td>
                            <button class="btn btn-outline-primary" data-no=${c.no}>+</button>
                            <span>${c.count}</span>
                            <button class="btn btn-outline-primaty" data-no=${c.no}>-</button>
                        </td>
                        <td>
                            ${c.total}원
                        </td>
                        <td>
                            <button class="btn btn-outline-danger" data-no=${c.no}>삭제</button>
                        </td>
                    </tr>
                `;
                $('#tbody').append(template);
                let totalPrice = 0;
                for(const cart of carts) {
                    totalPrice += cart.total;
                }
                $('#total_price').text(totalPrice);
            })
        })
    </script>
</head>
<body>
    <table class="table table-hover">
        <thead>
            <tr>
                <th>상품명</th>
                <th>개수</th>
                <th>구매가격</th>
            </tr>
        </thead>
        <tbody id="tbody">
            
        </tbody>
    </table>
    <p>총액: <span id="total_price"></span></p>
</body>
</html>
  • tbody: 전역 특성포함
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <title>할일 관리 앱</title> 
    <script>
        const todos = [
            {no: 1, title: '자바과제', content: '자바팀플 주제선정', date: '2020-11-20', isFinish: false},
            {no: 2, title: '오라클 과제', content: 'SQL CRUD 처리', date: '2020-11-30', isFinish: false},
        ];
        function sample() {
            return { irum: '홍길동', nai: 20};
        }

        $(document).ready(function() {
            $('#add').on('click', function() {
                // 구조 분해 할당 : 객체를 풀어헤쳐 변수로
                const {irum, nai} = sample();
                console.log(irum + ' ' + nai);

                const title = $('#title').val();
                const content = $('#content').val();
                if(title==='' || content==='') {
                    swal.fire('추가실패', '제목과 내용은 필수입력입니다', 'error');
                    return;
                }
                /*
                    const name = "홍길동";
                    const nai = 20;
                    const saram = { name: name, nai: nai };
                    // 구조 분해 할당 : 변수를 모아서 객체로
                    const saram = {name, nai};
                */
                const job = {title, content};
                job.no = 3;
                job.date = moment().format('YYYY-MM-DD');
                job.isFinish = false;
                todos.push(job);
                console.log(todos);
            })
        })
    </script>
</head>
<body>
    <label for="title">제목</label>
    <input type="text" id="title" placeholder="할 일 제목 입력">
    <label for="content">내용</label>
    <input type="text" id="content" placeholder="할 일 내용 입력">
    <button id="add">추가</button>
</body>
</html>
  • Sweet Alert: 일반 경고창보다 이쁜 경고창

  • fire: 버튼을 화면상에서 누르지 않아도, addBt를 눌렀을 때 발생하는 내부의 코드를 실행시켜줍니다.
    fire가 "불"이란 뜻이외에 사격에서 "발사시키다"라는 뜻도 가지고 있는 데,
    이때 코드에서 "발사시키다"라는 것은 버튼이벤트 내부의 코드를 인위적으로 실행시킨다(=발사시킨다)라는 의미로 받아들이시면 됩니다.

  • moment: moment() 함수를 사용해 현재 날짜와 시간 객체를 생성할 수 있습니다.

  • push: .push() : 배열의 맨 끝에 값을 추가한다.

<다듬기>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <title>추가 기능 다듬기</title> 
    <style>
        .finish { text-decoration: line-through;}
        .not_finish { text-decoration: none;}
    </style>
    <script>
        let no = 3;
        const todos = [
            {no: 1, title: '자바과제', content: '자바팀플 주제선정', date: '2020-11-20', isFinish: true},
            {no: 2, title: '오라클 과제', content: 'SQL CRUD 처리', date: '2020-11-30', isFinish: false},
        ];
        
        function add() {
            const title = $('#title').val();
            const content = $('#content').val();
            if(title==='' || content==='') {
                Swal.fire('오류 발생', '제목과 내용은 필수입력', 'error');
                return;
            }
            todos.push({no:no++, title:title, content:content, date:moment().format('YYYY-MM-DD'), isFinish:false});
            console.log(todos);
        }

        function showTodos() {
            const $tbody = $('#tbody');
            $tbody.empty();
            $.each(todos, function(i, t) {
                const btnStr = t.isFinish===true? '완료취소' : '완료하기';
                const classStr = t.isFinish===true? 'finish' : 'not_finish'
                const template = `
                    <tr>
                        <td>${t.no}</td>
                        <td>${t.title}</td>
                        <td class=${classStr}>${t.content}</td>
                        <td>${t.date}</td>
                        <td>
                            <button class="toggle" data-no=${t.no}>${btnStr}</button>
                            <button class="delete" data-no=${t.no}>삭제하기</button>
                        </td>
                    </tr>
                `;
                $tbody.append(template);
            })
        }

        $(document).ready(function() {
            showTodos();

            // 제목, 내용입력하고 버튼을 누르거나 엔터를 입력하면 추가하자
            $('#add').on('click', add);

            $('#title, #content').on('keyup', function(e) {
                // 글자가 없는 키(엔터, 공백, 백스페이스, 방향키)는 키의 숫자값(keyCode)로 비교할 수 있다
                // computer가 정말 이해하는 데이터는 숫자뿐. 65->'A', 48->'0'
                if(e.keyCode===13)
                add();
            });

            $('#tbody').on('click', '.toggle', function(e) {
                const no = parseInt(e.target.dataset.no);
                for(const t of todos) {
                    if(t.no===no) {
                        t.isFinish = !t.isFinish;
                    }
                }
                showTodos();
            });
        })
    </script>
</head>
<body>
    <label for="title">제목</label>
    <input type="text" id="title" placeholder="할 일 제목 입력">
    <label for="content">내용</label>
    <input type="text" id="content" placeholder="할 일 내용 입력">
    <button id="add">추가</button>
    <hr>
    <table class="table table-hover">
        <thead>
            <tr>
                <th>번호</th>
                <th>제목</th>
                <th>내용</th>
                <th>날짜</th>
                <th></th>
            </tr>
        </thead>
        <tbody id="tbody">

        </tbody>
    </table>
</body>
</html>
  • text-decoration: 선으로 텍스트를 꾸밀 수 있게 해주는 속성입니다.
    none : 선을 만들지 않습니다.
    line-through : 글자 중간에 선을 만듭니다.
    overline : 글자 위에 선을 만듭니다.
    underline : 글자 아래에 선을 만듭니다.
    initial : 기본값으로 설정합니다.
    inherit : 부모 요소의 속성값을 상속받습니다.
  • .finish(): 선택한 요소에서 실행 중인 모든 이펙트 효과를 즉시 중지시키고, 선택한 요소가 포함된 큐까지 제거하여 모든 이펙트 효과를 전부 종료시킨다.
  • .empty(): 선택한 요소의 내용을 지웁니다. 내용만 지울 뿐 태그는 남아있다는 것에 주의합니다.
  • .append(): 선택된 요소의 마지막에 새로운 요소나 콘텐츠를 추가한다.
  • keyup(): 눌렸던 키보드 키가 위로 올리갈 때 이벤트 발생.
  • hr 태그: 콘텐츠 내용에서 주제가 바뀔 때 사용할 수 있는 수평 가로선을 정의할 때 사용합니다.
  • e.keyCode===13 : 엔터키

<이해 안가>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <title>개수 증가</title>
    <script>
        // 개수 증가 이벤트를 처리하다보니 printCart의 매개변수가 잘못됐다는 사실을 알았다
        // printCarts에서 carts 전체를 출력하도록 하자
        const carts=[
            {no:122, name:'신라면', price:4100, count:1, total:4100},
            {no:357, name:'페레로로쉐 5T', price:3500, count:1, total:3500},
            {no:1113, name:'오레오', price:1200, count:1, total:1200}
        ];
        function printCarts() {
            $('#tbody').empty();
            $.each(carts, function(i, c) {
                const template = `
                    <tr>
                        <td>${c.name}</td>
                        <td>
                            <button class="btn btn-outline-primary inc" data-no=${c.no}>+</button>
                            <span>${c.count}</span>
                            <button class="btn btn-outline-primary dec" data-no=${c.no}>-</button>
                        </td>
                        <td>
                            ${c.total}원
                        </td>
                        <td>
                            <button class="btn btn-outline-danger delete" data-no=${c.no}>삭제</button>
                        </td>
                    </tr>
                `;
                $('#tbody').append(template); 
            });
            // totalPrice 출력하는 코드를 $.each에서 꺼냈음
            let totalPrice = 0;

            for(const cart of carts) {
                totalPrice += cart.total;
            }
            $('#total_price').text(totalPrice);
        }

        $(document).ready(function() {
            // printCarts() 함수는 반복문에서 cart를 하나씩 넘겨줘야지..하고 만들었는데
            // 버튼 이벤트 처리하다 보니까 cart를 하나씩 넘겨줄 수가 없네..
            
            printCarts();
            
            $('#tbody').on('click', '.inc', function(e) {
                // js로 데이터 속성에 접근하기
                let no = e.target.dataset.no;
                //+나 - 눌렀을때 총가격 바꾸기
                for(const cart of carts) {
                    no = parseInt(no);
                    if(cart.no===no) {
                        cart.count++;
                        cart.total=cart.total+cart.price;
                    }
                }
                printCarts();
            });
            //- 누르면 알림창 뜨기
            $('#tbody').on('click', '.dec', function(e) {
                const $dec = $(e.target);
                alert($dec.attr('data-no'));
            });
            $('#tbody').on('click', '.delete', function(e) {
                // 배열에 값을 집어넣을 때는 push
                // 배열에서 값을 삭제할 때는 splice(위치, 개수)
                const no = parseInt(e.target.dataset.no);
                for(let i=0; i<carts.length; i++) {
                    if(carts[i].no===no) {
                        carts.splice(i, 1);
                        printCarts();
                        return;
                    }
                }
            })
        })
    </script>
</head>
<body>
    <table class="table table-hover">
        <thead>
            <tr>
                <th>상품명</th>
                <th>개수</th>
                <th>구매가격</th>
            </tr>
        </thead>
        <tbody id="tbody">
            
        </tbody>
    </table>
    <p>총액: <span id="total_price"></span></p>
</body>
</html>


<JS의 타입>

1.기본 타입
2.참조 타입

  • 자바스크립트 내장 객체(브라우저의 자바스크립트 엔진에 내장된 객체를 말한다.) : Date
  • 객체 : this

->타입은 JS가 판단한다

		// 문자열 기본타입
        const a = 'hello';
        // new를 사용하면 내장 객체
        const s = new String('hello');

<문자열 다루기>

<script>
      const str = "hello 자바와 자바스크립트";
      console.log(str.includes("h")); //true
      console.log(str.indexOf(" "));  //5
      console.log(str.lastIndexOf(" ")); //9
      // 첫번째부터 두번째까지
      console.log(str.substring(1, 4)); //ell
      // 첫번째부터 4개
      console.log(str.substr(1, 4));  //ello
      // 매개변수를 하나만 주면 끝까지 자른다
      console.log(str.substr(5));// 자바와 자바스크립트

      const ar = [1, 3, 5];
      //java에서 contains
      console.log(ar.includes(4));
      console.log(ar.includes(3));
    </script>

*띄어쓴 것도 포함

  • indexOf: 특정문자 위치 찾기
  • last indexOf: 특정문자가 마지막에 있는 위치/찾지 못하면 -1을 반환합니다. 인덱스 카운터는 0부터 시작합니다.
  • substring: string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환합니다.
  • substr: (1,4)->인덱스 1~4 반환 / (5)-> 5부터 끝까지 자른다.

    <함수>
 <script>
      const a = 10;
      const b = function hello() {
        console.log("안녕하세요");
      };
      b();
      //hell(); ->hello 라는 이름은 사용하지 못한다.

      // 함수를 대입하면 원래 함수 이름은 사용불가능 -> 익명 함수
      const c = function () {
        console.log("익명함수입니다.");
      };
      // 화살표 함수는 익명함수만 만들수 있다.
      const d = () => console.log("화살표 함수");
      c(); //이렇게 부를 수 있고 hello(); 이렇게 못 부른다구
      d();
    </script>
    <script>
      const sum = function (a, b) {
        return a + b;
      };
      //화살표함수를 적을땐 function 대신에 =>를 사용한다.
      const mul = (a, b) => {
        return a * b;
      };
      const div = (a, b) => a / b; 
      //이땐 return도 생략함 한줄짜리 함수일땐 {}안쓰고, return 생략

      const a = 10;
      const b = 3;
      // 사용자가 1을 입력하면 덧셈, 2를 입력하면 곱셈, 3을 입력하면 나눗셈을 수행해 출력

      //계산 후 출력을 할때 어떤걸 계산할지 몰라서 func에 기능을 받아와서 ()붙여서 실행
      // -> 전략패턴 : ex)자판기 -> 서버, 프레임워크
      // js에서 함수는 일급 객체이므로 다른 함수의 매개변수가 될수있다.
      function calcAndprint(func) {
        console.log(func()); //func() ->()때문에 이건 함수이다.
      }
    </script>
  • js에서 함수는 일급 객체이므로 다른 함수의 매개변수가 될수있다.

<모르겠음>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <title>Document</title>
    <script>
      const key = "YbDgCwysjyv6GuBcOcAvJdXkcqFivrE";
      let page = 0;
      const url = `https://qpi.nytimes.com/svc/search/v2/articlesearch.json?q=election&page=${page}&api-key=${key}`;
      $(document).ready(async function () {
        try {
          const result = await $.ajax(url);
          console.log(result);
          $.each(result.response.docs, function (idx, article) {
            const html = ` <div class = 'card' style='e'`;
          });
        } catch (err) {
          console.log(err);
        }

        $(document).scroll(async function (e) {});
      });
    </script>
  </head>
  <body></body>
</html>

<Ajax (Asynchronous JavaScript and XML)>

  • 자바스크립트를 이용해서 비동기식으로 XML을 이용하여 서버와 통신하는 방식
  • 최근에는 XML 보다 JSON을 더 많이 사용한다.
  • 비동기식이란 여러가지 일이 동시적으로 발생한다는 뜻으로, 서버와 통신하는 동안 다른 작업을 할 수 있다는 의미

<Ajax의 동작방식>

  • 요청 : 브라우저는 서버에 정보를 요청한다. (브라우저는 Ajax요청을 담당하는 XMLHttpRequest 라는 객체를 구현하고 있다.)
  • 서버의 동작 : 서버는 응답으로 데이터를 전달한다. (XML, JSON)
    응답 : 브라우저는 콘텐츠를 처리하여 페이지에 추가한다.

<jQuery를 이용한 Ajax>

jQuery를 이용하여 Ajax를 사용하게 되면 많은 이점이 있습니다. 일단 Ajax의 기본 Method를 이용해서 Server와 통신을 하면 상당히 복잡합니다. 이는 XMLHttpRequest를 직접 사용하기 때문인데, jQuery를 이용하면 100줄 정도의 Source를 몇 줄 만으로 간단하게 Server와 Data를 주고 받을 수 있습니다. 또한 크로스브라우징의 문제를 jQuery가 알아서 해결해주며 여러가지 편리한 기능들을 제공하기 때문입니다.

jQuery에서 제공하는 $.ajax([settings])함수 는 다음과 같은 구조로 구성되어 있습니다.


  • await: await연산자는 Promise를 기다리기 위해 사용됩니다. 연산자는 async function 내부에서만 사용할 수 있습니다.
profile
안녕하세요

0개의 댓글