티스토리 뷰

개발냥이/자바스크립트(Javascript)

Ajax 입문

데브캣_DevCat 2022. 7. 25. 00:12

Ajax 기본골격

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

 

Ajax 연습 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;
        }

        .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 (i = 0; i < rows.length; i++) {
                        let gu_name = rows[i]['MSRSTE_NM']
                        let gu_mise = rows[i]['IDEX_MVL']
                        let names = ``
                        if (gu_mise >= 90) {
                            names = `<li class="bad">${gu_name} : ${gu_mise}</li>`
                        } else {
                            names = `<li>${gu_name} : ${gu_mise}</li>`
                        }
                        $('#names-q1').append(names)
                    }
                }
            })
        }
    </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>

# request 패키지

import requests # requests 라이브러리 설치 필요

r = requests.get('http://spartacodingclub.shop/sparta_api/seoulair')
rjson = r.json()

gus = rjson['RealtimeCityAir']['row']

for gu in gus:
	if gu['IDEX_MVL'] < 60:
		print (gu['MSRSTE_NM'], gu['IDEX_MVL'])

 

Ajax 연습 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;
        }

        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 txt = response['getStationList']['row']
                    for (i = 0; i < txt.length; i++) {
                        let location = txt[i]['stationName']
                        let total = txt[i]['rackTotCnt']
                        let parking = txt[i]['parkingBikeTotCnt']
                        let naming = ``;
                        if (parking <= 5) {
                            naming = `<tr>
                            <td>${location}</td>
                            <td>${total}</td>
                            <td class="bad">${parking}</td>
                        </tr>`
                        } else {
                            naming = `<tr>
                            <td>${location}</td>
                            <td>${total}</td>
                            <td>${parking}</td>
                        </tr>`
                        }

                        $('#names-q1').append(naming);
                    }
                }
            })
        }
    </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>

 

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>
반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함