본문 바로가기

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

스파르타 코딩클럽 웹개발 2주차

[수업 목표]

  1. Javascript 문법에 익숙해진다.
  2. jQuery로 간단한 HTML을 조작할 수 있다.
  3. Ajax로 서버 API(약속)에 데이터를 주고, 결과를 받아온다.

01. 2주차 오늘 배울 것

1) 2주차: jQuery, Ajax

더보기

오늘은 HTML파일을 받았다고 가정하고, Javascript로 다시 서버에 데이터를 요청하고 받는 방법을 배워볼거예요. jQuery를 이용해 Javascript로 HTML을 쉽게 제어하고, Ajax를 이용해 다시 서버에 데이터를 요청하고 받아보겠습니다.

2) Javascript 잠깐 복습 - 홀짝 판별 onclick 함수 만들어보기

더보기
let even = 4;
console.log(even % 2); // 2로 나눈 나머지가 0입니다.
let odd = 5;
console.log(odd % 2); // 2로 나눈 나머지가 1입니다.
    <script>
        let count = 1;
        function hey() {
            if (count % 2 == 0) {
                alert('짝짝짝👏');
            } else {
                alert('홀홀홀🎅');
            }
						count += 1;
        }
    </script>

02. JQuery

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

더보기

 jQuery는 Javascript와 다른 특별한 소프트웨어가 아니라 미리 작성된 Javascript 코드입니다. 전문 개발자들이 짜둔 코드를 잘 가져와서 사용하는 것임을 기억해주세요! (그렇게 때문에, 쓰기 전에 "임포트"를 해야합니다!)

 

Javascript로 길고 복잡하게 써야 하는 것을

document.getElementById("element").style.display = "none";

jQuery로 보다 직관적으로 쓸 수 있어요. 편리하죠? :-)

$('#element').hide();

2) 자주쓰는 jQuery

1. input 박스의 값을 가져와보기

더보기
<div class="form-floating mb-3">
    <input id="url" type="email" class="form-control" placeholder="name@example.com">
    <label>영화URL</label>
</div>
// 크롬 개발자도구 콘솔창에서 쳐보기
// id 값이 url인 곳을 가리키고, val()로 값을 가져온다.
$('#url').val();

// 입력할때는?
$('#url').val('이렇게 하면 입력이 가능하지만!');

2. 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 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 type="button" class="btn btn-outline-dark">닫기</button>
    </div>
</div>
// 크롬 개발자도구 콘솔창에 쳐보기
// id 값이 post-box인 곳을 가리키고, hide()로 안보이게 한다.
$('#post-box').hide();

// show()로 보이게 한다.
$('#post-box').show();

 

3. 태그 내 html 입력하기

  • <div> ~ </div> 내에, 동적으로 html을 넣고 싶을 땐? (예를 들어, 포스팅되면 → 카드 추가)
  • 카드가 붙는 div 에 id를 추가해주는 것이 핵심!
더보기
<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);

2) 버튼 말고, 카드를 넣어보기

// 주의: 홑따옴표(')가 아닌 backtick(`)으로 감싸야 합니다.
// 숫자 1번 키 왼쪽의 버튼을 누르면 backtick(`)이 입력됩니다.
// backtick을 사용하면 문자 중간에 Javascript 변수를 삽입할 수 있습니다.
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);

4. 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 {
            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>
        $.ajax({
            type: "GET",
            url: "http://spartacodingclub.shop/sparta_api/seoulair",
            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']
                    console.log(gu_name,gu_mise)
                }
            }
        })
        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 type="email" class="form-control" id="url" placeholder="name@example.com">
        <label for="floatingInput">영화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 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 id="cards-box" class="row row-cols-1 row-cols-md-4 g-4">
        <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>

5. Quiz_JQuery 연습하기

(1)

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

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

        function q3() {
            let txt = $('#input-q3').val()
            let temp_html = `<li>${txt}</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) 답안코드

더보기
<!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의 입력값을 가져온다.
            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>

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

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

1)서버→클라이언트: "JSON"을 이해하기

더보기

2) 클라이언트→서버: GET 요청 이해하기

더보기

👉 API는 은행 창구와 같은 것!

같은 예금 창구에서도 개인 고객이냐 기업 고객이냐에 따라 가져와야 하는 것 / 처리해주는 것이 다른 것처럼,

클라이언트가 요청 할 때에도, "타입"이라는 것이 존재합니다.

  • GET → 통상적으로! 데이터 조회(Read)를 요청할 때 예) 영화 목록 조회
  • POST → 통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때 예) 회원가입, 회원탈퇴, 비밀번호 수정

이 중에서 오늘은 GET 방식에 대해 배워보겠습니다. (POST는 4주차에 배웁니다)

  • GET
더보기
<https://movie.naver.com/movie/bi/mi/basic.nhn?code=161967>

위 주소는 크게 두 부분으로 쪼개집니다. 바로 "?"가 쪼개지는 지점인데요.
"?" 기준으로 앞부분이 <서버 주소>, 뒷부분이 [영화 번호] 입니다.

* 서버 주소: <https://movie.naver.com/movie/bi/mi/basic.nhn>
* 영화 정보: code=161967

👉 GET 방식으로 데이터를 전달하는 방법

? : 여기서부터 전달할 데이터가 작성된다는 의미입니다. & : 전달할 데이터가 더 있다는 뜻입니다.

예시) google.com/search?q=아이폰&sourceid=chrome&ie=UTF-8

     위 주소는 google.com의 search 창구에 다음 정보를 전달합니다!
     q=아이폰                        (검색어)
     sourceid=chrome        (브라우저 정보)
     ie=UTF-8                      (인코딩 정보)

👉 여기서 잠깐, 그럼 code라는 이름으로 영화번호를 주자!는 것은 누가 정하는 것일까요?

→ 네, 바로 프론트엔드 개발자와 백엔드 개발자가 미리 정해둔 약속입니다.

프론트엔드: "code라는 이름으로 영화번호를 주면 될까요?"

백엔드: "네 그렇게 하시죠. 그럼 code로 영화번호가 들어온다고 생각하고 코딩하고 있을게요"

04. Ajax

1) Ajax 기본 골격

$.ajax({
  type: "GET", // GET 방식으로 요청한다.
  url: "<http://spartacodingclub.shop/sparta_api/seoulair>",
  data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
  success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
    console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
  }
})

2) $ajax 코드 설명

더보기
  • type: "GET" → GET 방식으로 요청한다.
  • url: 요청할 url
  • data: 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
리마인드 GET 요청은, url뒤에 아래와 같이 붙여서 데이터를 가져갑니다.
http://naver.com?param=value¶m2=value2

POST 요청은, data : {} 에 넣어서 데이터를 가져갑니다.
data: { param: 'value', param2: 'value2' },
  • success: 성공하면, response 값에 서버의 결과 값을 담아서 함수를 실행한다.
success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
  console.log(response) 
}

3) 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기

업데이트 버튼 누를 때 마다 갱신, 미세먼지 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;
        }
    </style>

    <script>
        function q1() {
            $('#names-q1').empty()
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/seoulair",
                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> 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>

4) 서울시 OpenAPI(실시간 따릉이 현황)을 이용하기

현재 거치된 따릉이가 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;
        }

        .urgent{
         color: red;
        }
    </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 name = rows[i][`stationName`]
              let rack = rows[i][`rackTotCnt`]
              let bike = rows[i][`parkingBikeTotCnt`]

              let temp_html = ``

              if (bike < 5) {
                temp_html = `<tr class="urgent">
                        <td>${name}</td>
                        <td>${rack}</td>
                        <td>${bike}</td>
                </tr>`
              } else {
                temp_html = `<tr>
                        <td>${name}</td>
                        <td>${rack}</td>
                        <td>${bike}</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>

5) 랜덤 르탄이 API를 이용하기

[르탄이 나와] 버튼을 누를 때 마다 다른 르탄이와 대사가 나옵니다.

더보기
<!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 url = response['url']
            let msg = response['msg']
            $('#img-rtan').attr('src',url)
            $('#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>

05. 2주차 숙제

1주차에 완성한 팬명록에 날씨 정보를 넣어주세요! 

로딩이 완료되면,날씨API을 이용해서 날씨를 표시해주세요.

◎  HINT

더보기

👻 로딩 완료 후 환율을 써주려면 어떻게 해야할까요? 먼저, "javascript 로딩 후 실행"이라고 검색해볼까요?

새로고침 할 때 마다 실시간으로 현재기온 표시

더보기
<!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.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=Noto+Sans+KR&family=Roboto:wght@300&display=swap" rel="stylesheet">
    <style>
        * {
            font-family: 'Noto Sans KR', sans-serif;
        }
        .mypic {
            width: 100%;
            height: 300px;

            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.3)), url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgdrn6GTwF7fSA9HBj2vKmyN_4YvY-hENhJQ&usqp=CAU');
            background-position: center 30%;
            background-size: cover;

            color: white;

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

        .mypost {
            width: 95%;
            max-width: 500px;
            margin: 20px auto 20px auto;

            box-shadow: 0px 0px 3px 0px black;
            padding: 20px;
        }

        .mypost > button {
            margin-top: 15px;
        }

        .mycards {
            width: 95%;
            max-width: 500px;
            margin: auto;
        }

        .mycards > .card {
            margin-top: 10px;
            margin-bottom: 10px;
        }
    </style>
    <script>
        $(document).ready(function(){
            $.ajax({
              type: "GET",
              url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
              data: {},
              success: function(response){
                  $('#temp').text(response['temp'])
                }
              })
        });
    </script>
</head>
<body>
    <div class="mypic">
        <h1>성시경 팬명록</h1>
        <p>현재기온: <span id="temp">00.00</span>도</p>
    </div>
    <div class="mypost">
        <div class="form-floating mb-3">
            <input type="text" class="form-control" id="name" placeholder="url">
            <label for="floatingInput">닉네임</label>
        </div>
        <div class="form-floating">
            <textarea class="form-control" placeholder="Leave a comment here" id="comment"
                style="height: 100px"></textarea>
            <label for="floatingTextarea2">응원댓글</label>
        </div>
        <button onclick="save_comment()" type="button" class="btn btn-dark">응원 남기기</button>
    </div>
    <div class="mycards" id="comment-list">
        <div class="card">
            <div class="card-body">
                <blockquote class="blockquote mb-0">
                    <p>새로운 앨범 너무 멋져요!</p>
                    <footer class="blockquote-footer">오로지</footer>
                </blockquote>
            </div>
        </div>
        <div class="card">
            <div class="card-body">
                <blockquote class="blockquote mb-0">
                    <p>새로운 앨범 너무 멋져요!</p>
                    <footer class="blockquote-footer">오호라</footer>
                </blockquote>
            </div>
        </div>
        <div class="card">
            <div class="card-body">
                <blockquote class="blockquote mb-0">
                    <p>새로운 앨범 너무 멋져요!</p>
                    <footer class="blockquote-footer">오히려</footer>
                </blockquote>
            </div>
        </div>
    </div>
</body>
</html>