그저 내가 되었고

항해99) 웹종 2주차 jQuery+Javascript 연습 & jQuery+Ajax 연습 본문

개발/항해99 9기

항해99) 웹종 2주차 jQuery+Javascript 연습 & jQuery+Ajax 연습

hyuunii 2022. 9. 5. 08:32

* jQuery+Javascript 연습

사전 준비) 1.제이쿼리 임포트  2.부트스트랩 연동

1&2 완료한 시작 템플릿::

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

    <title>스파르타코딩클럽</title>
</head>

<body>
    <h1>꼬우</h1>
</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;
        }
    </style>

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

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

        function q3() {
            // 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() {
            // 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>

이거를ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ let 변수...를 어떻게 줘야하는지 모르겠어섴ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ

괜찮아!!!! 배울때 오래 걸리는건 너무 괜찮음. 제대로 배우기만 하면 된다. 걱정마. 익숙해질거야.

 

 <script>
        function q1() {
          $('#input-q1').val()
            if($('#input-q1').val() == '') {
              alert('입력하세요!')
            } else {
              alert($('#input-q1').val())
            }
        }

        function q2() {
          $('#input-q2').val()
            if($('#input-q2').val().includes('@')) {
              alert($('#input-q2').val().split('@')[1].split('.')[0])
            } else {
              alert('이메일 아님')
            }
        }

        function q3() {
          $('#input-q3').val()   //답안에서는 input-q3 값을 가져오기 위해 let newName = $('#input-q3').val(); 이런 식으로 newName이란 변수를 줌)
          let temp_html = `<li>${$('#input-q3').val()}</li>`
          $('#names-q3').append(temp_html)
      }

        function q3_remove() {
           $('#names-q3').empty()
        }

    </script>

이렇게 함... 잘 굴러가니 됐잖아요..........?ㅎ...................................

아래는 답안ㅋ

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


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


        function q3() {
// 1. input-q3 값을 가져온다.
            let newName = $('#input-q3').val();
            if (newName == '') {
                alert('이름을 입력하세요');
                return;
            }
// 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다. (let temp_html = `<li>${가져온 값}</li>`)
            let temp_html = `<li>${newName}</li>`;
// 3. 만들어둔 temp_html을 names-q3에 붙인다.(jQuery의 $('...').append(temp_html)을 이용하면 굿!)
            $('#names-q3').append(temp_html);
        }

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

    </script

* jQuery+Ajax 연습((하나만 할거면 맨 마지막 '스파르타피디아에 OpenAPI 붙여보기' 이거))

Ajax 기본 골격

$.ajax({
  type: "GET",
  url: "여기에URL을입력",
  data: {},
  success: function(response){
    console.log(response)
  }
})

미세먼지 OpenAPI: http://spartacodingclub.shop/sparta_api/seoulair

+ 미세먼지 수치가 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;
        }
    </style>

    <script>
        function q1() {
            // 여기에 코드를 입력하세요
        }
    </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>

답안👇🏻

<!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;
        }

        .soso {
            color: orange;
        }

    </style>

    <script>
        function q1() {
            $('#names-q1').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 = "soso">${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>

 


따릉이 OpenAPI:: http://spartacodingclub.shop/sparta_api/seoulbike

+ 따릉이 대수가 5대 미만인 곳은 빨갛게?

 

템플릿👇🏻

<!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() {
            // 여기에 코드를 입력하세요
        }
    </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>

답안👇🏻

<!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 rack_name = rows[i]['stationName'];
                        let rack_cnt = rows[i]['rackTotCnt'];
                        let bike_cnt = rows[i]['parkingBikeTotCnt'];
                        let temp_html = '';
                        if (bike_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>

 


르탄이 API:: http://spartacodingclub.shop/sparta_api/rtan

👻 힌트 : 이미지 바꾸기 / 텍스트 바꾸기
  • 이미지 바꾸기 : $("#아이디값").attr("src", 이미지URL);
  • 텍스트 바꾸기 : $("#아이디값").text("바꾸고 싶은 텍스트");

 

템플릿👇🏻

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

              let msg = response['msg'];
              $("#text-rtan").text(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>

4. 스파르타피디아에 OpenAPI 붙여보기

1. 2주차에 완성했던 '스파르타 피디아'를 켜자(골격이쥬)

<!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 {
            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>
</div>
<div class="mypost" 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>
    </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>

 

2. 로드가 다 되면 실행되는 함수 만들기

참고)) document.ready

<script>
	$(document).ready(function(){
    
    });
</script>

document.ready는 window.onload와 다르게 태그의 로드만을 감지. window.load보다 조금 더 빠르게 실행되고 중복 사용하여 실행해도 전부 다 실행할 수 있다는 장점이 있다.

 

함수 작성))

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

function listing() {
	console.log('화면 로딩 후 잘 실행되었습니다');
}

 

3. API 결과값을 다시한번 확인하기

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

function listing() {
	$.ajax({
	  type: "GET",
	  url: "http://spartacodingclub.shop/web/api/movie",
	  data: {},
	  success: function(response){
			console.log(response)
	  }
	})
}

 

4. 영화 데이터를 console에 찍어보기

$.ajax({
  type: "GET",
  url: "http://spartacodingclub.shop/web/api/movie",
  data: {},
  success: function(response){
        console.log(response['movies'])
  }
})

 

5. movies를 돌면서, 하나씩 출력

$.ajax({
  type: "GET",
  url: "http://spartacodingclub.shop/web/api/movie",
  data: {},
  success: function(response){
        let movies = response['movies']
        for (let i = 0 ; i < movies.length; i++) {
            let movie = movies[i]
            console.log(movie)
        }
  }
})

 

6. movie 내용을 (image, comment, title, desc, star) 가지고 HTML을 만들어 붙임

$.ajax({
    type: "GET",
    url: "http://spartacodingclub.shop/web/api/movie",
    data: {},
    success: function(response){
          let movies = response['movies']
          for (let i = 0 ; i < movies.length; i++) {
              let movie = movies[i]
              let title = movie['title']
              let desc = movie['desc']
              let image = movie['image']
              let comment = movie['comment']
              let star = movie['star']

              let temp_html = `<div class="col">
                                  <div class="card h-100">
                                      <img src="${image}"
                                           class="card-img-top">
                                      <div class="card-body">
                                          <h5 class="card-title">${title}</h5>
                                          <p class="card-text">${desc}</p>
                                          <p>${star}</p>
                                          <p class="mycomment">${comment}</p>
                                      </div>
                                  </div>
                              </div>`
              $('#cards-box').append(temp_html)
          }
    }
  })

 

7. 별을 그려서 붙임

🍡let star_image = '⭐'.repeat(star) 을 사용하기!
$.ajax({
    type: "GET",
    url: "http://spartacodingclub.shop/web/api/movie",
    data: {},
    success: function(response){
          let movies = response['movies']
          for (let i = 0 ; i < movies.length; i++) {
              let movie = movies[i]
              let title = movie['title']
              let desc = movie['desc']
              let image = movie['image']
              let comment = movie['comment']
              let star = movie['star']

              let star_image = '⭐'.repeat(star)

              let temp_html = `<div class="col">
                                  <div class="card h-100">
                                      <img src="${image}"
                                           class="card-img-top">
                                      <div class="card-body">
                                          <h5 class="card-title">${title}</h5>
                                          <p class="card-text">${desc}</p>
                                          <p>${star_image}</p>
                                          <p class="mycomment">${comment}</p>
                                      </div>
                                  </div>
                              </div>`
              $('#cards-box').append(temp_html)
          }
    }
  })

 

8. 먼저 있던 카드들을 지움

$('#cards-box').empty();

 

9. 완성된 전체 코드!!

<!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 {
            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>
        $(document).ready(function(){
          listing();
        });

        function listing() {
            $('#cards-box').empty()
            $.ajax({
              type: "GET",
              url: "http://spartacodingclub.shop/web/api/movie",
              data: {},
              success: function(response){
                    let movies = response['movies']
                    for (let i = 0 ; i < movies.length; i++) {
                        let movie = movies[i]
                        let title = movie['title']
                        let desc = movie['desc']
                        let image = movie['image']
                        let comment = movie['comment']
                        let star = movie['star']

                        let star_image = '⭐'.repeat(star)

                        let temp_html = `<div class="col">
                                            <div class="card h-100">
                                                <img src="${image}"
                                                     class="card-img-top">
                                                <div class="card-body">
                                                    <h5 class="card-title">${title}</h5>
                                                    <p class="card-text">${desc}</p>
                                                    <p>${star_image}</p>
                                                    <p class="mycomment">${comment}</p>
                                                </div>
                                            </div>
                                        </div>`
                        $('#cards-box').append(temp_html)
                    }
              }
            })
        }

        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>
</div>
<div class="mypost" 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>
    </div>
</div>
<div class="mycards">
    <div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">
    </div>
</div>
</body>

</html>