ETC -

jQuery + Ajax

  • -

안녕하세요 TriplexLab 입니다.
오늘은 jQuery + Ajax 관해서 살펴보도록 하겠습니다.
FE개발들 사이에서 역사로 남고 있는 jQuery + Ajax 기술을 왜 글을 작성하냐고요??
역사로 남게 될거니깐!! 정리하는 차원으로 이 글을 작성 합니다.
몇 십년을 웹시장에서 주름잡았던 jQuery + Ajax 기술 간단하게 요약해 봅니다.

👉jQuery + Ajax

Ajax는 서버로에게 비동기 요청을 보낼수 있는 방식중에 하나 입니다.
종류는 크게 4가지가 있습니다.
GET, POST, PUT, DELETE가 있는데, Ajax는 이러한 방식으로 API를 요청할 수 있도록 도와주는 라이브러리이다.

GET : 데이터 요청 
POST : 데이터 추가 
PUT : 데이터 수정 
DELETE : 데이터 삭제

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
    const getData = () => {
        $.ajax({
            type: "GET",
            url: '...',
            data: {},
            success: (res) => {
                console.log(res);
            }
        });
    };
</script>

type : API 요청 방식(GET, POST, PUT, DELETE)
url : API 서버의 URL
data : POST, PUT, DELETE 요청 시 서버로 넘겨줄 데이터(Object)
success : 요청 성공 시 실행할 콜백함수

 

👉jQuery + Ajax 실습


🎯서울시 실시간 미세먼지 OpenAPI 사용

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

조건식을 사용해서 미세먼지 수치가 70이상인 곳은 빨갛게 보여줍시다.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
    function q1() {
        $.ajax({
            type: "GET",
            url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
            data: {},
            success: function (response) {
                const rows = response["RealtimeCityAir"]["row"];
                const temp = rows.map((el) => {
                    const {MSRSTE_NM, IDEX_MVL} = el;
                    let temp_html = ''
                    if (IDEX_MVL > 70) {
                        temp_html = `<li class="bad">${MSRSTE_NM} : ${IDEX_MVL}</li>`
                    } else {
                        temp_html = `<li>${MSRSTE_NM} : ${IDEX_MVL}</li>`
                    }
                    return temp_html;
                }).join('');
                $('#names-q1').html(temp);
            }
        })
    }
</script>

 

🎯서울시 실시간 따릉이 현황 OpenAPI 사용

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

조건식을 사용해서 따릉이 대수가 5대 미만인 곳은 빨갛게 보여줍시다.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
    function q1() {
        $.ajax({
            type: "GET",
            url: "http://spartacodingclub.shop/sparta_api/seoulbike",
            data: {},
            success: function (response) {
                const rows = response["getStationList"]["row"];
                const temp = rows.map((el) => {
                    const {stationName, rackTotCnt, parkingBikeTotCnt} = el;
                    let temp_html = '';
                    if (parkingBikeTotCnt < 5) {
                        temp_html = `<tr class="urgent">
                            <td>${stationName}</td>
                            <td>${rackTotCnt}</td>
                            <td>${parkingBikeTotCnt}</td>
                          </tr>`
                    } else {
                        temp_html = `<tr>
                            <td>${stationName}</td>
                            <td>${rackTotCnt}</td>
                            <td>${parkingBikeTotCnt}</td>
                          </tr>`
                    }
                    return temp_html;
                }).join('');
                $('#names-q1').html(temp);
            }
        })
    }
</script>

 

👉마무리하며


위에 코드에 관해서 조금 이야기를 하자면 나는  jquery에서 append 메소드를 사용해서 템블릿을 뿌려주는것은 비효율적이라 생각해서
[안티 패턴] html메소드로 한번에 뿌려주었습니다.

자 이렇게 jQuery와 Ajax에 대해서 살펴봤습니다.
개인적으로 open API요청 개념은 어떻게 보면 웹 개발의 진짜 시작이라고 할수 있습니다.
왜냐하면 비로서 클라이언트와 서버가 서로 소통을 하는데 약속을 정해서 어떻게 요청하고, 어떻게 받을 것인지 등등의 개념을 알수 있기 
때문 입니다.

이번 시간에는 open API에서 받아와 화면서 뿌려주는것만 해봤는데 다음 글에는 클라이언트에서 데이터를 담아 서버에 보내어 DB에 저장하는것도 해보겠습니다.🔥🔥

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.