항해 99/사전 기본 스터디

WIL _ Ajax 활용

U_D 2022. 2. 23. 19:13
할 때는 익숙하지만 계속 잊게된다...
let을 기본으로 사용하는거에 익숙해져야 할거같다.
row 데이터가 여러값일 때는 필요한 부분만을 추출하기 위해 rows를 설정하는듯
온도나, 르탄이(이미지,텍스트) 처럼 하나의값에서 받아오는? 형태는 다른 태그를 활용했다.

 

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

  • 클라이언트→서버 : GET 요청 이해하기
API는 은행 창구와 같은 것! 같은 예금 창구에서도 개인 고객이냐 기업 고객이냐에 따라 가져와야 하는 것

처리해주는 것이 다른 것처럼, 클라이언트가 요청 할 때에도, "타입"이라는 것이 존재

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

 

 

 

2. Ajax 기본 골격

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

 

3. Ajax 연습하기 _ 1

  • 실시간 미세먼지 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;
        }
    </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 = `<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>

 

  • 미세먼지 기준이 50 이상일 때 빨간색으로 표시하기

<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 > 50) {
                            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>

 

4. Ajax 연습하기 _ 2

  • 서울시 OpenAPI (실시간 따릉이 현황)을 이용해서 다시 한번 연습하기.

거치된 따릉이 수가 10대 미만인 곳은 빨갛게 표시

 

<!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;
        }
        .bad {
            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 station = rows[i]['stationName']
                        let rack = rows[i]['rackTotCnt']
                        let bike = rows[i]['parkingBikeTotCnt']

                        let temp_html = ``

                        if (bike < 10) {
                            temp_html = `<tr class="bad">
                                            <td>${station}</td>
                                            <td>${rack}</td>
                                            <td>${bike}</td>
                                        </tr>`
                        }   else {
                            temp_html = `<tr>
                                            <td>${station}</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. Ajax 연습하기 _ 3

  • 개인적으로 가장 재미있었던 그림과 문자 바꾸기!
  • 르탄이 나와 버튼을 누를때마다 그림과 그림을 설명하는 멘트가 바뀐다
이미지 바꾸기 : $("#아이디값").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() {
            $.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>

 

 

6. Ajax 연습하기 _ 4

  • 팬명록에 현재온도 실시간으로 반영하기
텍스트 바꾸기 : $("#아이디값").text("바꾸고 싶은 텍스트");

<!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>
        .mytitle {
            height: 200px;
            width: 100%;
            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://img.vogue.co.kr/vogue/2021/12/style_61c299401f4b3-1200x801.jpeg");
            background-position: center;
            background-size: 40%;

            color: white;

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

            margin: 20px auto 20px auto;

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

        .mybtn {
            margin: 10px auto 0px auto;
        }

        .card {
            max-width: 500px;
            width: 95%;

            margin: 20px auto 20px auto;
        }
    </style>
    <script>
        $.ajax({
            type: "GET",
            url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
            data: {},
            success: function (response) {
                $("#temp").text(response['temp']);
            }
        })
    </script>

</head>

<body>
    <div class='mytitle'>
        <h1>아이유 팬명록</h1>
        <p>현재 기온 : <span id="temp">00.00</span>도</p>
    </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="form-floating">
            <textarea class="form-control" placeholder="Leave a comment here" id="floatingTextarea2"
                      style="height: 100px"></textarea>
            <label for="floatingTextarea2">응원댓글</label>
        </div>
        <div class="mybtn">
            <button type="button" class="btn btn-dark">응원 남기기</button>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <blockquote class="blockquote mb-0">
                <p>새로운 앨범 너무 멋져요!</p>
                <footer class="blockquote-footer">삼촌팬</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>
</body>

</html>