*/스파르타코딩클럽 웹개발종합반

[스파르타코딩클럽 | 웹개발종합반] 2주차: JQuery, Ajax, API

sssbin 2021. 9. 13. 00:13

 

1. JQuery

  ✔️ Javascript → 라이브러리 (미리 작성된 Javascript 코드)

  ✔️ import 필요

 

  - input 박스 값 가져오기

$('#article-url').val()

  - div 보이기/숨기기

$('#posting-box').show()
$('#posting-box').hide()

  - css 값 가져오기

$('#cards-box').css('width') //"cards-box"의 width 가지고 옴
$('#cards-box').css('width', '700px') //"cards-box"의 width를 700px로 바꿈

$('#posting-box').css('display') --> "block" (보임) / "none" (안 보임)

  - 태그 내 텍스트 입력하기

$('#article-url').val('hihi') //input 박스
$('#btn-posting-box').text('포스팅 박스 닫기'); //다른 박스 (ex. 버튼)

  - 태그 내 html 입력하기

let temp_html = `<button> 버튼 추가 </button>` //backtick
$('#cards-box').append(temp_html);

 

  ▶ JQuery 연습하기

<!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() {
            let inputValue = $('#input-q1').val();
            if (inputValue == '') {
                alert('입력하세요!');
            }
            else {
                alert(inputValue);
            }
            // 1. input-q1의 입력값을 가져온다. $('# .... ').val() 이렇게!
            // 2. 만약 입력값이 빈칸이면 if(입력값=='')
            // 3. alert('입력하세요!') 띄우기
            // 4. alert(입력값) 띄우기
        }

        function q2() {
            let inputEmail = $('#input-q2').val();
            if (inputEmail.includes('@')) {
                let domain = inputEmail.split('@')[1].split('.')[0];
                alert(domain);
            }
            else {
                alert('이메일이 아닙니다.');
            }
            // 1. input-q2 값을 가져온다.
            // 2. 만약 가져온 값에 @가 있으면 (includes 이용하기 - 구글링!)
            // 3. info.spartacoding@gmail.com -> gmail 만 추출해서 ( .split('@') 을 이용하자!)
            // 4. alert(도메인 값);으로 띄우기
            // 5. 만약 이메일이 아니면 '이메일이 아닙니다.' 라는 얼럿 띄우기
        }

        function q3() {
            let inputName = $('#input-q3').val();
            let temp_html = `<li> ${inputName} </li>`;
            $('#names-q3').append(temp_html);
            // 1. input-q3 값을 가져온다. let txt = ... q1, q2에서 했던 걸 참고!
            // 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다. (let temp_html = `<li>${txt}</li>`) 요렇게!
            // 3. 만들어둔 temp_html을 names-q3에 붙인다.(jQuery의 $('...').append(temp_html)을 이용하면 굿!)
        }

        function q3_remove() {
            $('#names-q3').empty();
            // 1. names-q3의 내부 태그를 모두 비운다.(jQuery의 $('....').empty()를 이용하면 굿!)
        }

    </script>

</head>

<body>
    <h1>jQuery + Javascript의 조합을 연습하자!</h1>

    <div class="question-box">
        <h2>1. 빈칸 체크 함수 만들기</h2>
        <h5>1-1. 버튼을 눌렀을 때 입력한 글자로 얼럿 띄우기</h5>
        <h5>[완성본]1-2. 버튼을 눌렀을 때 칸에 아무것도 없으면 "입력하세요!" 얼럿 띄우기</h5>
        <input id="input-q1" type="text" /> <button onclick="q1()">클릭</button>
    </div>
    <hr />
    <div class="question-box">
        <h2>2. 이메일 판별 함수 만들기</h2>
        <h5>2-1. 버튼을 눌렀을 때 입력받은 이메일로 얼럿 띄우기</h5>
        <h5>2-2. 이메일이 아니면(@가 없으면) '이메일이 아닙니다'라는 얼럿 띄우기</h5>
        <h5>[완성본]2-3. 이메일 도메인만 얼럿 띄우기</h5>
        <input id="input-q2" type="text" /> <button onclick="q2()">클릭</button>
    </div>
    <hr />
    <div class="question-box">
        <h2>3. HTML 붙이기/지우기 연습</h2>
        <h5>3-1. 이름을 입력하면 아래 나오게 하기</h5>
        <h5>[완성본]3-2. 다지우기 버튼을 만들기</h5>
        <input id="input-q3" type="text" placeholder="여기에 이름을 입력" />
        <button onclick="q3()">이름 붙이기</button>
        <button onclick="q3_remove()">다지우기</button>
        <ul id="names-q3">
            <li>세종대왕</li>
            <li>임꺽정</li>
        </ul>
    </div>
</body>

</html>

 

2. Ajax

  - 서버 → 클라이언트

       ㄴ "JSON" - Key:Value

  - 클라이언트 → 서버

       ㄴ GET : 데이터 조회

       ㄴ POST : 데이터 생성, 변경, 삭제

 

  - Ajax는 jQuery를 import한 페이지에서만 동작 가능

  - Ajax 기본 골격

$.ajax({
  type: "GET", //GET 방식으로 요청
  url: "여기에URL을입력",
  data: {}, //요청하면서 함께 줄 데이터 (GET일 때는 비워두기)
  success: function(response){ //서버에서 준 결과->response에 담음
    console.log(response)
  }
})

 

  ▶ 02_ajaxquiz01.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;
        }

        .bad {
            color : red;
        }
    </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>

</head>

<body>
    <h1>jQuery+Ajax의 조합을 연습하자!</h1>

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

</html>

  ▶ 02_ajaxquiz02.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;
        }

        table {
            border: 1px solid;
            border-collapse: collapse;
        }

        td,
        th {
            padding: 10px;
            border: 1px solid;
        }

        .red {
            color : red;
            font-weight : bold;
        }
    </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 stationName = rows[i]['stationName']
                        let rackTotCnt = rows[i]['rackTotCnt']
                        let parkingBikeTotCnt = rows[i]['parkingBikeTotCnt']

                        let temp_html = ``
                        if (parkingBikeTotCnt < 5) {
                            temp_html = `<tr class="red">
                                        <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)
                    }
                }
            })
        }
    </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">
                <tr>
                    <td>102. 망원역 1번출구 앞</td>
                    <td>22</td>
                    <td>0</td>
                </tr>
                <tr>
                    <td>103. 망원역 2번출구 앞</td>
                    <td>16</td>
                    <td>0</td>
                </tr>
                <tr>
                    <td>104. 합정역 1번출구 앞</td>
                    <td>16</td>
                    <td>0</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>

</html>

  ▶ 02_ajaxquiz03.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 image = response[0]['url']
                    $("#img-cat").attr("src",image)
                }
            })
      }
    </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>

 

 

 

3. 숙제: 환율 표시

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>

    <title>스파르타코딩클럽 | 부트스트랩 연습하기</title>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Song+Myung&family=Stylish&display=swap" rel="stylesheet">

    <style>
        * {
            font-family: 'Song Myung', serif;
            font-family: 'Stylish', sans-serif;
        }

        .photo {
            text-align : center;
        }

        .content_title {
            padding : 20px 300px 0px 300px;
        }

        .content_rate {
            padding : 20px 300px 0px 300px;
            color : blue;
        }

        .content_order {
            padding : 20px 500px 0px 300px;
        }

        .title {
            font-size : 50px;
            font-weight : bold;
        }

        .size {
            width : 200px;
            height : 20px;
            float : right;
        }

        .button {
            width : 200px;
            margin : auto;
            display : block;
        }
    </style>

    <script>
        function order() {
            alert('주문이 완료되었습니다.');
        }

        function q1() {
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/rate",
                data: {},
                success: function (response) {
                    let rate = response['rate']
                    $("#rate").append(rate)
                }
            })
        }

        $(document).ready(function () {
            q1();
        })

    </script>
</head>

<body>
    <div>
        <div class="photo">
            <img src="http://swiki.cafe24.com/web/product/big/201808/653369f1193cfcf3d01894d870a6cd59.jpg" width="360px" height="320px"/>
        </div>

        <div class="content_title">
            <div>
                <span class="title"> 상품제목 </span> 가격: 10,000원 / 개
            </div>

            <div>
                집안을 밝게 비춰주는 형광등이 꺼지고, 방 안에 어둠이 내릴 때, 은은한 빛으로 따뜻하게 공간을 감싸주는 무드등 하나 만으로 집안 분위기가 바뀔 수 있다.
            </div>
        </div>

        <div class="content_rate" id="rate"> 달러-원 환율: </div>

        <div class="content_order">
            <div class="title"> 주문하기 </div>

            <div>
                <label for="name"> 주문자 성함: </label>
                <input type="text" id="name" class="size" />
            </div>

            <div>
                <label for="number"> 수량: </label>
                <input class="size" list="datalistOptions" id="number" placeholder="수량을 입력하세요">
                <datalist id="datalistOptions" >
                    <option value="1">
                    <option value="2">
                    <option value="3">
                    <option value="4">
                    <option value="5">
                </datalist>
            </div>

            <div>
                <label for="address"> 주소: </label>
                <input type="text" id="address" class="size" />
            </div>

            <div>
                <label for="phone"> 전화번호: </label>
                <input type="tel" id="phone" class="size" />
            </div>
        </div>

        <div>
            <button onclick="order()" class="button"> 주문하기 </button>
        </div>
    </div>

</body>

</html>