Everyday Dev System

웹개발 종합반 2일차 - 2 본문

내배캠 초기 학습/웹개발 종합반

웹개발 종합반 2일차 - 2

chaeyoung- 2023. 5. 9. 18:42

5:50 pm - 6:40 pm

 

Fetch를 이용해서 데이터 가져오기

Fetch란?

url을 통해 정보를 가져와서 json형태로 만들어서 이를 활용함

        fetch("여기에 URL을 입력").then(res => res.json()).then(data => {
            console.log(data)
        })

 

Fetch 연습하기 코드

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

jQuery 활용을 위해 해당 코드 반드시 입력하여 import해야 함.

 

연습 1

URL : http://spartacodingclub.shop/sparta_api/seoulair

Base code :

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

<head>
    <meta charset="UTF-8">
    <title>Fetch 시작하기</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        fetch("여기에 URL을 입력").then(res => res.json()).then(data => {
            console.log(data)
        })
    </script>
</head>

<body>
    Fetch 연습을 위한 페이지
</body>

</html>

 

 

정답 :

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

<head>
    <meta charset="UTF-8">
    <title>Fetch 시작하기</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
            let rows = data['RealtimeCityAir']['row']
            rows.forEach((a)=> {
                console.log(a['MSRSTE_NM'],a['CO'])
            })
        })
    </script>
</head>

<body>
    Fetch 연습을 위한 페이지
</body>

</html>

 

연습 2

- 업데이트를 누르면 자치구에 따른 미세먼지 농도 출력

- 미세먼지 농도가 40이상인 자치구의 글자 색상을 빨강색으로 나타나도록 해라

 

URL : http://spartacodingclub.shop/sparta_api/seoulair

Base code :

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

<head>
    <meta charset="UTF-8">
    <title>미세먼지 API로Fetch 연습하고 가기!</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.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>Fetch 연습하자!</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>미세먼지 API로Fetch 연습하고 가기!</title>

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

    <style type="text/css">
        div.question-box {
            margin: 10px 0 20px 0;
        }
        .bad{
            color : red;
        }
    </style>

    <script>
        function q1() {
            fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
                let rows = data['RealtimeCityAir']['row']
                $('#names-q1').empty()

                rows.forEach((a)=> {
                    let gu_name = a['MSRSTE_NM']
                    let gu_mise = a['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>Fetch 연습하자!</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>

 

 

연습 3

- 정류장 이름, 따릉이 거치대 수 , 현 따릉이 갯수 출력

- 현재 따릉이가 5개 미만인 곳은 빨강색으로 보이도록 하여라

 

URL : http://spartacodingclub.shop/sparta_api/seoulbike

Base code

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

<head>
    <meta charset="UTF-8">
    <title>Fetch 연습하고 가기!</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>Fetch 연습하자!</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>Fetch 연습하고 가기!</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;
        }
    </style>

    <script>
        function q1() {
            fetch("http://spartacodingclub.shop/sparta_api/seoulbike").then(res => res.json()).then(data => {
                let rows = data['getStationList']['row']
                $('#names-q1').empty()

                rows.forEach((a) => {
                    let name = a['stationName']
                    let rack = a['rackTotCnt']
                    let parkingBike = a['parkingBikeTotCnt']

                    let temp_html = ``
                    if (parkingBike < 5) {
                        temp_html = `<tr class="red">
                                            <td>${name}</td>
                                            <td>${rack}</td>
                                            <td>${parkingBike}</td>
                                        </tr>`
                    } else {
                        temp_html = `<tr>
                                            <td>${name}</td>
                                            <td>${rack}</td>
                                            <td>${parkingBike}</td>
                                        </tr>`
                    }
                    $('#names-q1').append(temp_html)
                })
            })

        }
    </script>

</head>

<body>
    <h1>Fetch 연습하자!</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>

 

 

연습 4

 

서울 온도 출력하기

Base Code :

<!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>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap');

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

        .mytitle {
            background-color: green;
            color: white;

            height: 250px;

            display: flex;
            flex-direction: column;
            /* column 새로 정렬 , row 가로 정렬 */
            align-items: center;
            justify-content: center;

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

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

            background-color: transparent;

            border: 1px solid white;
            color: white;

            border-radius: 50px;
            margin-top: 20px;

        }

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

        .mycomment {
            color: gray;
        }

        .mycards {
            width: 1200px;
            margin: 20px auto 20px auto;
        }

        .mypost {
            width: 500px;
            margin: 20px auto 20px auto;

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

        .mybtn {
            display: flex;
            flex-direction: row;
            /* column 새로 정렬 , row 가로 정렬 */
            align-items: center;
            justify-content: center;

            margin-top: 20px;
        }

        .mybtn>button {
            margin-right: 10px;
        }
    </style>
    <script>
        $(document).ready(function () {
            fetch("http://spartacodingclub.shop/sparta_api/weather/seoul").then(res => res.json()).then(data => {

            })
        })

    </script>
</head>

<body>
    <div class="mytitle">
        <h1>내 생애 최고의 영화들!!</h1>
        <div>현재 서울의 날씨 : <span id="temp">20</span>도</div>
        <button class="mybtn" onclick="hey()">영화 기록하기</button>
    </div>
    <div class="mypost">
        <div class="form-floating mb-3">
            <input type="email" class="form-control" id="floatingInput" 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="3">⭐⭐⭐⭐</option>
                <option value="3">⭐⭐⭐⭐⭐</option>
            </select>
        </div>
        <div class="form-floating">
            <textarea class="form-control" placeholder="Leave a comment here" id="floatingTextarea"></textarea>
            <label for="floatingTextarea">코멘트</label>
        </div>
        <div class="mybtn">
            <button type="button" class="btn btn-dark">기록하기</button>
            <button 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">
            <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>

 

정답:

        $(document).ready(function () {
            fetch("http://spartacodingclub.shop/sparta_api/weather/seoul").then(res => res.json()).then(data => {
                let temp = data['temp']
                $('#temp').text(temp)
            })
        })

 

 

fetch를 이용하여 영화 포스터 append 시키기.

URL : http://spartacodingclub.shop/web/api/movie

<!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>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap');

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

        .mytitle {
            background-color: green;
            color: white;

            height: 250px;

            display: flex;
            flex-direction: column;
            /* column 새로 정렬 , row 가로 정렬 */
            align-items: center;
            justify-content: center;

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

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

            background-color: transparent;

            border: 1px solid white;
            color: white;

            border-radius: 50px;
            margin-top: 20px;

        }

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

        .mycomment {
            color: gray;
        }

        .mycards {
            width: 1200px;
            margin: 20px auto 20px auto;
        }

        .mypost {
            width: 500px;
            margin: 20px auto 20px auto;

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

        .mybtn {
            display: flex;
            flex-direction: row;
            /* column 새로 정렬 , row 가로 정렬 */
            align-items: center;
            justify-content: center;

            margin-top: 20px;
        }

        .mybtn>button {
            margin-right: 10px;
        }
    </style>
    <script>
        $(document).ready(function () {
            fetch("http://spartacodingclub.shop/sparta_api/weather/seoul").then(res => res.json()).then(data => {
                let temp = data['temp']
                $('#temp').text(temp)
            })

            fetch("http://spartacodingclub.shop/web/api/movie").then(res => res.json()).then(data => {
                let rows = data['movies']
                $('#cards').empty()
                rows.forEach((a) => {
                    let title = a['title']
                    let desc = a['desc']
                    let comment = a['comment']
                    let star = a['star']
                    let image = a['image']
                    let star_image = '⭐'.repeat(star)

                    let temp_html = `<div class="col">
                                        <div class="card h-100">
                                            <img src="${image}"
                                                class="card-img-top" alt="...">
                                            <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').append(temp_html)
                })
            })
        })

    </script>
</head>

<body>
    <div class="mytitle">
        <h1>내 생애 최고의 영화들!!</h1>
        <div>현재 서울의 날씨 : <span id="temp">20</span>도</div>
        <button class="mybtn" onclick="hey()">영화 기록하기</button>
    </div>
    <div class="mypost">
        <div class="form-floating mb-3">
            <input type="email" class="form-control" id="floatingInput" 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="3">⭐⭐⭐⭐</option>
                <option value="3">⭐⭐⭐⭐⭐</option>
            </select>
        </div>
        <div class="form-floating">
            <textarea class="form-control" placeholder="Leave a comment here" id="floatingTextarea"></textarea>
            <label for="floatingTextarea">코멘트</label>
        </div>
        <div class="mybtn">
            <button type="button" class="btn btn-dark">기록하기</button>
            <button type="button" class="btn btn-outline-dark">닫기</button>
        </div>
    </div>

    <div class="mycards">
        <div id="cards" 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>

결과:

'내배캠 초기 학습 > 웹개발 종합반' 카테고리의 다른 글

웹개발 종합반 4일차 -1  (0) 2023.05.12
웹개발 종합반 3일차 -2  (0) 2023.05.10
웹개발 종합반 3일차 -1  (1) 2023.05.10
웹개발 종합반 2일차 -1  (0) 2023.05.09
웹개발 종합반 1일차  (0) 2023.05.03