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

웹개발종합반 개발일지 | 2주차 - 6,7,8,9,10,11강

이모냥냥 2022. 8. 16. 11:00
반응형

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

 

 

2022.08.16 - [스파르타코딩클럽/웹개발종합반] - 웹개발 종합반 개발일지 | 2주차 - 1,2,3,4,5강

 

웹개발 종합반 개발일지 | 2주차 - 1,2,3,4,5강

💡수업 목표💡 Javascript 문법에 익숙해진다. jQuery로 간단한 HTML을 조작할 수 있다. Ajax로 서버 API(약속)에 데이터를 주고, 결과를 받아온다. jQuery란? : 오픈 소스 기반의 자바스크립트 라이브러리

sosohan-coding.tistory.com

 


 

서버-클라이언트 통신

웹은 크게 클라이어트와 서버로 나뉘어져서 서로 통신을 통해서 데이터를 주고 받는다. 클라이언트가 웹서비스를 통해서 데이터를 전송하고 (Request) 서버는 클라이언트가 전송한 데이터를 받아서 처리한 후 처리한 데이터를 HTML파일로 응답한다.(Response)

json이란

:JavaScript Object Notation이라는 의미ㄹ, JavaScript에서 데이터를 저장하거나 전송할때 많이 사용하는 형식이다.

JSON은, Key:Value로 이루어져 있습니다. 자료형 Dictionary와 아주- 유사하다.

 

 

전송방법 GET/POST

API, 서버-클라이언트 통신은 은행창구와 같이 같은 예금 창구에서라도 개인이냐 기업이냐에 따라서 처리하는 방법이 다른 것처럼,클라이언트 -> 서버 로 요청할때에도 "타입"이라는 것이 존재한다.

데이터 전송방법은 HTTP 요청 메소드를 따른다. GET, POST외에도 여러가지가 있지만 네크워크적인 부분이라서 굳이 알필요 없다.

GET (정보를 가져오는 것)
: 서버에서 어떤 데이터를 가져와서 보여준다는 의미. 통상적으로 데이터 조회(Read)를 요청할때

- URL 뒤에 데이터 노출
- URL 뒤에 노출되기 때문에 글자수 제한
- URL 뒤에 노출되기 때문에 보안취약
POST(정보를 전송하는것)
: 서버의 값이나 상태를 바꾸기 위해서 사용한다는 의미.통상적으로 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할때 사용

- URL 노출 없이 숨겨서 전송
- URL 노출이 아니라서 글자 수 제한이 없음
- URL 노출이 아니라서 보안

 

이번에 2주차에서는 GET을 배우고 4주차에서 POST를 배울 예정이다.

 

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 (인코딩 정보)

 

 

 

Ajax

https://api.jquery.com/jQuery.ajax/

 

jQuery.ajax() | jQuery API Documentation

Description: Perform an asynchronous HTTP (Ajax) request. The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available

api.jquery.com

Ajax 기본 구조

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

setting는 Ajax 통신을 위한 옵션을 담고 있는 객체가 들어간다.

  • type : 데이터를 전송하는 방법을 지정한다. get, post를 사용할 수 있다.
  • url : 데이터를 전송하는 url을 지정한다.
  • data : 서버로 데이터를 전송할 때 이 옵션을 사용한다.
  • success : 성공했을 때 호출할 콜백 함수을 지정한다. Function( PlainObject data, String textStatus, jqXHR jqXHR )
    성공하면, response 값에 서버의 결과값을 담아서 함수를 실행한다.
  • error : 실패했을 때 호출할 콜백 함수을 지정한다.

 

예제01 - 미세먼지 OpenAPI

http://spartacodingclub.shop/ajaxquiz/01

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

<head>
    <meta charset="UTF-8">
    <title>미세먼지 OpenAPI</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() {
// 여기에 코드를 입력하세요
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/seoulair",
                data: {},
                success: function (response) {
                    console.log(response)
                    let rows = response['RealtimeCityAir']['row'];
                    $("#names-q1").empty();
                    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);

                        let temp_html;
                        if(gu_mise > 120){
                            temp_html =`<li class="bad">${gu_name} : ${gu_mise}</li>`;
                        }else{
                            temp_html =`<li>${gu_name} : ${gu_mise}</li>`;
                        }


                        $("#names-q1").append(temp_html);
                    }
                }
            })
        }
    </script>

</head>

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

<hr/>

<div class="question-box">
    <h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
    <p>모든 구의 미세먼지를 표기해주세요</p>
    <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
    <button onclick="q1()">업데이트</button>
    <ul id="names-q1">
<!--        <li>중구 : 82</li>-->
<!--        <li>종로구 : 87</li>-->
<!--        <li>용산구 : 84</li>-->
<!--        <li>은평구 : 82</li>-->
    </ul>
</div>
</body>

</html>

 

예제02 - 실시간 따릉이 OpenAPI

http://spartacodingclub.shop/ajaxquiz/02_2

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

<head>
    <meta charset="UTF-8">
    <title>실시간 따릉이 OpenAPI</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() {
// 여기에 코드를 입력하세요
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/seoulbike",
                data: {},
                success: function (response) {
                    console.log(response)
                    let rows = response['getStationList']['row'];
                    $("#names-q1").empty();
                    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>
                            <td>${name}</td>
                            <td>${rack}</td>
                            <td class="urgent">${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">
        <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>

 

예제03 - 랜덤 르탄이 API

http://spartacodingclub.shop/ajaxquiz/08

<!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) {
                    console.log(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>

 

 

HW02. 팬명록 날씨 API

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

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

    <title>스파르타코딩클럽 | 세븐틴 팬명록</title>
    <style>
        * {
            font-family: 'Gowun Dodum', sans-serif;
        }

        .myTitle {
            background-color: darkgreen;
            width: 100%;
            height: 250px;
            color: #fff;
            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://img.hankyung.com/photo/202205/03.30135835.1.jpg");
            background-position: center;
            background-size: cover;

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

        .wrap {
            width: 95%;
            max-width: 500px;
            margin: 20px auto 0px;
        }

        .myPost {
            width: 95%;
            max-width: 500px;
            box-shadow: 0px 0px 3px 0px gray;
            padding: 20px;
            margin: 20px auto;
        }

        .mybtn {
            margin: 10px 0;
        }
    </style>
    <script>
        $(document).ready(function() {
            alert('다 로딩됐다!');
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
                data: {},
                success: function (response) {
                    console.log(response)
                    $("#curr_temp").text(response['temp']);

                }
            })
        });
    </script>
</head>

<body>
<div class="myTitle">
    <h1>세븐틴 팬명록</h1>
    <p>현재기온 : <span id="curr_temp">0</span>도</p>
</div>
<div class="myPost">
    <div class="form-floating mb-3">
        <input type="text" class="form-control" id="floatingInput" placeholder="name@example.com">
        <label for="floatingInput">닉네임</label>
    </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>
    </div>
</div>
<div class="wrap">
    <div class="row row-cols-1 row-cols-md-1 g-4">
        <div class="col">
            <div class="card">
                <div class="card-body">
                    <blockquote class="blockquote mb-0">
                        <p>사랑해요</p>
                        <footer class="blockquote-footer">캐럿</footer>
                    </blockquote>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card">
                <div class="card-body">
                    <blockquote class="blockquote mb-0">
                        <p>사랑해요</p>
                        <footer class="blockquote-footer">캐럿</footer>
                    </blockquote>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card">
                <div class="card-body">
                    <blockquote class="blockquote mb-0">
                        <p>사랑해요</p>
                        <footer class="blockquote-footer">캐럿</footer>
                    </blockquote>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card">
                <div class="card-body">
                    <blockquote class="blockquote mb-0">
                        <p>사랑해요</p>
                        <footer class="blockquote-footer">캐럿</footer>
                    </blockquote>
                </div>
            </div>
        </div>
        <div class="col">
           <div class="card">
                <div class="card-body">
                    <blockquote class="blockquote mb-0">
                        <p>사랑해요</p>
                        <footer class="blockquote-footer">캐럿</footer>
                    </blockquote>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

</html>

 

반응형