A ship in harbor is safe, but that is not what ships are built for.

개발일지/스파르타코딩클럽_웹개발

Day04(2-1~2-13)

플리피나리 2022. 8. 4. 09:57
반응형

1. 2주차 오늘 배울 것 : jQuery, Ajax

-> jQuery를 이용해 Javascript로 HTML을 쉽게 제어

-> Ajax를 이용해 다시 서버에 데이터 요청

 

 

2. jQuery 시작하기

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

- 코드 복잡성 & 브라우저 간 호환성 문제 해결

- 임포트 필요 : <head></head> 사이 

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

- 하지만, 부트스트랩 사용 시 임포트가 이미 되어있음

- jQuery에서 id 값을 이용해 특정 객체(버튼 or 인풋박스 or div 등)를 가리킴

 

 

3. jQuery 다뤄보기(1)

- 필요한 기능들은 그때그때 구글링!

- input 박스의 값 가져오기(val)

<input id="url" type="email" class="form-control" placeholder="name@example.com">
//id값이 url인 곳의 val 값 가져오기
$('#url').val();

//id값이 url인 곳에 val 값 입력하기
$('#url').val('이렇게 하면 입력이 가능하지만!');

- div 보이기/숨기기(show/hide)

<div class="mypost" id="post-box"> ... </div>
//id 값이 post-box인 곳을 hide()로 안 보이게 하기
$('#post-box').hide();

//id 값이 post-box인 곳을 show()로 보이게 하기
$('#post-box').show();

 

 

4. jQuery 다뤄보기(2)

- 태그 내 html 입력 -> 동적으로 html 넣고 싶을 때

<div class="mycards">
    <div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">
        <div class="col">
            <div class="card h-100">
                <img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
                     class="card-img-top" alt="...">
                <div class="card-body">
                    <h5 class="card-title">영화 제목이 들어갑니다</h5>
                    <p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
                    <p>⭐⭐⭐</p>
                    <p class="mycomment">나의 한줄 평을 씁니다</p>
                </div>
            </div>
        </div>
    </div>
</div>

1) 버튼 넣기

let temp_html = `<button>나는 추가될 버튼이다!</button>`;
$('#cards-box').append(temp_html);

*작은 따옴표가 아닌 백틱(backtick)임을 주의!

 

2) 카드 넣기

let title = '영화 제목이 들어갑니다';

let temp_html = `<div class="col">
				     <div class="card h-100">
				           <img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
				                     class="card-img-top" alt="...">
				           <div class="card-body">
				               <h5 class="card-title">${title}</h5>
				               <p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
				               <p>⭐⭐⭐</p>
				               <p class="mycomment">나의 한줄 평을 씁니다</p>
				           </div>
				     </div>
				</div>`;
$('#cards-box').append(temp_html);

 

 

5. jQuery 적용하기(포스팅 박스)

- '영화 기록하기' 버튼을 누르면 숨겨진 창이 나타나고, '닫기' 버튼을 누르면 사라진다.

<!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 href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
            crossorigin="anonymous"></script>

    <title>스파르타 피디아</title>

    <link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">

    <style>
        * {
            font-family: 'Gowun Dodum', sans-serif;
        }

        .mytitle {
            width: 100%;
            height: 250px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://movie-phinf.pstatic.net/20210715_95/1626338192428gTnJl_JPEG/movie_image.jpg');
            background-position: center;
            background-size: cover;

            color: white;

            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .mytitle > button {
            width: 200px;
            height: 50px;

            background-color: transparent;
            color: white;

            border-radius: 50px;
            border: 1px solid white;

            margin-top: 10px;
        }

        .mytitle > button:hover {
            border: 2px solid white;
        }

        .mycomment {
            color: gray;
        }

        .mycards {
            margin: 20px auto 0px auto;
            width: 95%;
            max-width: 1200px;
        }

        .mypost {  <!--css는 class로-->
            width: 95%;
            max-width: 500px;
            margin: 20px auto 0px auto;
            padding: 20px;
            box-shadow: 0px 0px 3px 0px gray;

            display: none;  <!--시작부터 감춰두기 속성-->
        }

        .mybtns {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;

            margin-top: 20px;
        }
        .mybtns > button {
            margin-right: 10px;
        }
    </style>
    <script>  
        function open_box(){  //포스팅 밗 제어함수
            $('#post-box').show()   
        }
        function close_box(){
            $('#post-box').hide()
        }
    </script>
</head>

<body>
<div class="mytitle">
    <h1>내 생애 최고의 영화들</h1>
    <button onclick="open_box()">영화 기록하기</button>  <!--onclick 속성값에 함수 설정-->
</div>
<div class="mypost" id="post-box">  <!--포스팅 박스의 id값 'post-box'-->
    <div class="form-floating mb-3">
        <input id="url" type="email" class="form-control" placeholder="name@example.com">
        <label>영화URL</label>
    </div>
    <div class="input-group mb-3">
        <label class="input-group-text" for="inputGroupSelect01">별점</label>
        <select class="form-select" id="inputGroupSelect01">
            <option selected>-- 선택하기 --</option>
            <option value="1">⭐</option>
            <option value="2">⭐⭐</option>
            <option value="3">⭐⭐⭐</option>
            <option value="4">⭐⭐⭐⭐</option>
            <option value="5">⭐⭐⭐⭐⭐</option>
        </select>
    </div>
    <div class="form-floating">
        <textarea id="comment" class="form-control" placeholder="Leave a comment here" id="floatingTextarea2"
                  style="height: 100px"></textarea>
        <label for="floatingTextarea2">코멘트</label>
    </div>
    <div class="mybtns">
        <button type="button" class="btn btn-dark">기록하기</button>
        <button onclick="close_box()" type="button" class="btn btn-outline-dark">닫기</button>
        <!--onclick 속성값에 함수 설정-->
    </div>
</div>
<div class="mycards">
    <div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">
        <div class="col">
            <div class="card h-100">
                <img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
                     class="card-img-top" alt="...">
                <div class="card-body">
                    <h5 class="card-title">영화 제목이 들어갑니다</h5>
                    <p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
                    <p>⭐⭐⭐</p>
                    <p class="mycomment">나의 한줄 평을 씁니다</p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card h-100">
                <img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
                     class="card-img-top" alt="...">
                <div class="card-body">
                    <h5 class="card-title">영화 제목이 들어갑니다</h5>
                    <p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
                    <p>⭐⭐⭐</p>
                    <p class="mycomment">나의 한줄 평을 씁니다</p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card h-100">
                <img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
                     class="card-img-top" alt="...">
                <div class="card-body">
                    <h5 class="card-title">영화 제목이 들어갑니다</h5>
                    <p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
                    <p>⭐⭐⭐</p>
                    <p class="mycomment">나의 한줄 평을 씁니다</p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card h-100">
                <img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
                     class="card-img-top" alt="...">
                <div class="card-body">
                    <h5 class="card-title">영화 제목이 들어갑니다</h5>
                    <p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
                    <p>⭐⭐⭐</p>
                    <p class="mycomment">나의 한줄 평을 씁니다</p>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

</html>

 

 

6. Quiz_jQuery 연습하기

- 퀴즈 완성본 : http://spartacodingclub.shop/ajaxquiz/00_0

 

jQuery 연습하고 가기!

 

spartacodingclub.shop

- 코드

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

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

        function q3() {
            let txt = $('#input-q3').val()  // 1. input-q3 값을 가져온다. let txt = ... q1, q2에서 했던 걸 참고!
            if (txt=='') {
               alert('이름을 입력하세요')
               return
            }
            let temp_html = `<li>${txt}</li>`  // 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다. (let temp_html = `<li>${txt}</li>`) 요렇게!
            $('names-q3').append(temp_html)  // 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>

*includes(searchString) 함수는 searchString이 배열의 요소로 발견되면 true를 반환하고, 찾을 수 없다면 false로 반환

 

 

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

- JSON은 Key:Value로 이루어져 자료형 Dictionary와 아주 유사 -> 딕셔너리형 value 내 또 딕셔너리가 들어있는 형태

- 클라이언트가 서버에 요청할 때 '타입'이 존재

- GET : 통상적으로 데이터 조회(Read) 요청 시

- POST : 통상적으로 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 시

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

   1) ? : 이것을 기준으로 앞부분이 <서버주소>, 뒷부분이 <전달할 데이터>

   2) & : 전달할 데이터가 더 있음을 의미

   ex) google.com/search?q=아이폰&sourceid=chrome&ie=UTF-8 -> google.com의 search 창구에 q=아이폰(검색어),                 sourceid=chrome(브라우저정보), ie=UTF-8(인코딩 정보) 정보 전달

*이런 데이터변수명(q, sourceid, ie, code 등)은 개발자가 정함

 

 

8. Ajax 시작하기

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

- Ajax 기본 골격

$.ajax({
   type: "GET",  //GET 방식 요청, POST라 하면 POST 방식 요청
   url: "여기에 URL을 입력",   //요청할 url
   data: {},   //요청하면서 함께 줄 데이터(GET 요청시엔 비워두기)
   success: function(response) {   //서버에서 준 결과를 response라는 변수에 담음
      console.log(response)   //서버에서 준 결과를 이용해 나머지 코드 작성
   }
});

- 구 이름과 미세먼지 수치 출력하기

$.ajax({
   type: "GET",
   url: "http://spartacodingclub.shop/sparta_api/seoulair",
   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 함께 연습하기

- 문제 완성본 : http://spartacodingclub.shop/ajaxquiz/01

 

JQuery 연습하고 가기!

1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기 모든 구의 미세먼지를 표기해주세요 업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다. 업데이트

spartacodingclub.shop

- 코드

<!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() {
            $('#names-ql').empty();
            $.ajax({
               type: "GET",
               url: "http://spartacodingclub.shop/sparta_api/seoulair",
               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"];
                     let 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">
        </ul>
    </div>
</body>

</html>

- 미세먼지 수치가 40이상인 곳 빨갛게

<!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;
            font-weight: bold;
        }
    </style>

    <script>
        function q1() {
            $('#names-ql').empty();
            $.ajax({
               type: "GET",
               url: "http://spartacodingclub.shop/sparta_api/seoulair",
               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"];
                     let temp_html = '';
                     
                     if (gu_mise > 40) {
                        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">
        </ul>
    </div>
</body>

</html>

 

 

10. Quiz_Ajax 연습하기(1)

- 문제 완성본 : http://spartacodingclub.shop/ajaxquiz/02_1

 

JQuery 연습하고 가기!

2. 서울시 OpenAPI(실시간 따릉기 현황)를 이용하기 모든 위치의 따릉이 현황을 보여주세요 업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다. 업데이트 거치대 위치 거치대 수 현재 거치

spartacodingclub.shop

- 코드

<!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;
        }
    </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 bike = rows[i];
                     let rack_name = bike["stationName"];
                     let rack_cnt = bike["rackTotCnt"];
                     let bike_cnt = bike["parkingBikeTotCnt"];
                     let temp_html = `<tr>
                                        <td>${rack_name}</td>
                                        <td>${rack_cnt}</td>
                                        <td>${bike_cnt}</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">
            </tbody>
        </table>
    </div>
</body>

</html>

 

 

11. Quiz_Ajax 연습하기(2)

- 따릉이 대수가 5대 미만인 곳은 빨갛게 표현

- 완성본 : http://spartacodingclub.shop/ajaxquiz/02_2

 

JQuery 연습하고 가기!

2. 서울시 OpenAPI(실시간 따릉기 현황)를 이용하기 모든 위치의 따릉이 현황을 보여주세요 업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다. 업데이트 거치대 위치 거치대 수 현재 거치

spartacodingclub.shop

- 코드

<!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;
        }
        .urgent {
            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 bike = rows[i];
                     let rack_name = bike["stationName"];
                     let rack_cnt = bike["rackTotCnt"];
                     let bike_cnt = bike["parkingBikeTotCnt"];
                     let temp_html = ''
                     if (rack_cnt < 5) {
                        temp_html = `<tr class='urgent'>
                                        <td>${rack_name}</td>
                                        <td>${rack_cnt}</td>
                                        <td>${bike_cnt}</td>
                                      </tr>`
                     } else {
                        temp_html = `<tr>
                                        <td>${rack_name}</td>
                                        <td>${rack_cnt}</td>
                                        <td>${bike_cnt}</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">
            </tbody>
        </table>
    </div>
</body>

</html>

 

 

12. Quiz_Ajax 연습하기(3)

- 완성본 : http://spartacodingclub.shop/ajaxquiz/08

 

JQuery 연습하고 가기!

3. 르탄이 API를 이용하기! 아래를 르탄이 사진으로 바꿔주세요 업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다. 르탄이 나와 나는 ㅇㅇㅇ하는 르탄이!

spartacodingclub.shop

- 코드

<!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: "http://spartacodingclub.shop/sparta_api/rtan",
           data: {},
           success: function (response) {
              $('#img-rtan').attr("src", response["url"]);
              $('#text-rtan').text(response["msg"]);
           }
        })
      }
    </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-rtan" width="300" src="http://spartacodingclub.shop/static/images/rtans/SpartaIcon11.png"/>
        <h1 id="text-rtan">나는 ㅇㅇㅇ하는 르탄이!</h1>
      </div>
    </div>
  </body>
</html>

*attr(attributeName) 함수는 선택한 요소의 속성값을 가져옴, attr(attributeName, value) 함수는 선택한 요소에 속성값을 추가함

**text() 함수는 선택한 요소 안의 내용을 가져옴(태그를 가져오는게 아님), text(textString) 함수는 이전 내용을 지우고 새로운 내용을 추가함

 

 

13. 2주차 숙제

- 1주차의 팬명록에 날씨 정보 추가

- 로딩 완료 후 호출하기

$(document).ready(function() {
   alert('다 로딩됐다!')
});

- 코드

<!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 href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>

    <title>스파르타코딩클럽 | 부트스트랩 연습하기</title>
    <link href="https://fonts.googleapis.com/css2?family=Jua&family=Nanum+Pen+Script&display=swap" rel="stylesheet">
    <style>
        * {
            font-family: 'Nanum Pen Script', cursive;
        }
        .mytitle {
            width: 100%;
            height: 250px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://cdn.mhnse.com/news/photo/202203/98608_81045_397.jpg");
            background-position: center;
            background-size: cover;

            color: white;

            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        .mypost {
            max-width: 500px;
            width: 95%;
            margin: 20px auto 20px auto;

            box-shadow: 0px 0px 3px 0px gray;
            padding: 20px;
        }
        .card {
            max-width: 500px;
            width: 95%;
            margin: 20px auto 0px auto;
        }
        .mybutton {
            margin-top: 15px;
        }
    </style>
    <script>
        $(document).ready(function() {
           $.ajax({
              type: "GET",
              url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
              data: {},
              success: function (response) {
                 let temp = response["temp"];
                 $('#temp').text(temp);
              }
           })
        });
    </script>
</head>

<body>
    <div class="mytitle">
        <h1>(여자)아이들((G)-IDLE) 팬명록</h1>
        <p>현재기온: <span id="temp">36</span>도</p>
    </div>
    <div class="mypost">
        <div class="form-floating mb-3">
            <input type="text" class="form-control" id="floatingInput" placeholder="username">
            <label for="floatingInput">닉네임</label>
        </div>
        <div class="form-floating">
            <textarea class="form-control" placeholder="Leave a comment here" id="floatingTextarea2"
                      style="height: 100px"></textarea>
            <label for="floatingTextarea2">응원댓글</label>
        </div>
        <div class="mybutton">
            <button type="button" class="btn btn-dark">응원 남기기</button>
        </div>
    </div>
    <div class="card">
        <div class="card-body">
            <blockquote class="blockquote mb-0">
                <p>새로운 앨범 너무 멋져요!</p>
                <footer class="blockquote-footer"><cite title="Source Title">호빵맨</cite>
                </footer>
            </blockquote>
        </div>
    </div>
    <div class="card">
        <div class="card-body">
            <blockquote class="blockquote mb-0">
                <p>새로운 앨범 너무 멋져요!</p>
                <footer class="blockquote-footer"><cite title="Source Title">호빵맨</cite>
                </footer>
            </blockquote>
        </div>
    </div>
    <div class="card">
        <div class="card-body">
            <blockquote class="blockquote mb-0">
                <p>새로운 앨범 너무 멋져요!</p>
                <footer class="blockquote-footer"><cite title="Source Title">호빵맨</cite>
                </footer>
            </blockquote>
        </div>
    </div>
</body>
</html>
반응형

'개발일지 > 스파르타코딩클럽_웹개발' 카테고리의 다른 글

Day06(4-1~4-14)  (0) 2022.08.09
Day05(3-1~3-13)  (0) 2022.08.05
Day03(1-14~1-20)  (0) 2022.07.02
Day02(1-3~1-13)  (0) 2022.07.02
Day01(1-1~1-2)  (0) 2022.07.02