본문 바로가기
웹 개발 공부중

ajax , json , jquery 다루기

by redeyes 2021. 12. 14.

Ajax는 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신할 수 있습니다. (비동기방식)

참고자료는 미세먼지 데이터이며 json 형태이며, 가져오는 방법은 javascript 로  new XMLHttpRequest(); 해서 

var xhr = new XMLHttpRequest();

xhr.open('post', 'url');
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {

            console.log(xhr.responseText);
        } else alert("요청오류 : " + xhr.status);
    }
}
xhr.send(form);

이렇게 가져올 수 있지만 jquery가 가독성이 편하다고 대부분이 jquery로 아래와 같이 사용합니다.

<!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']
                    console.log(response)
                    for (i = 0; i < rows.length; i++) {
                    <!-- response 콘솔값 확인하면 하위에 농도랑 구 이름을 확인 할 수 있다 -->
                        let gu_name = rows[i]['MSRSTE_NM'];
                        let gu_mise = rows[i]['IDEX_MVL'];
                        console.log(gu_name, gu_mise);

                        let temp_html = `<li>${gu_name} : ${gu_mise}</li>`;

                        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>

</head>

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

<hr/>

<div class="question-box">
    <h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
    <button onclick="q1()">업데이트</button>
    <ul id="names-q1">

    </ul>
</div>
</body>

</html>

WEB API : 웹 애플리케이션 개발에서 다른 서비스에 요청을 보내고 응답을 받기 위해 정의된 명세를 일컫는다. 예를 들어 블로그 API를 이용하면 블로그에 접속하지 않고도 다른 방법으로 글을 올릴 수 있다. 그 외에 우체국의 우편번호 API, 구글과 네이버의 지도 API등 유용한 API들이 많으므로, 요즘은 홈페이지 구축이나 추가개편 시 따로 추가로 개발하지 않고 이런 오픈 API를 가져와 사용하는 추세다. 

'웹 개발 공부중' 카테고리의 다른 글

ajax 온도 가져오기  (0) 2021.12.14
ajax 따릉이 데이터가져오기  (0) 2021.12.14
jQuery 이용해서 div박스 열고 닫기  (0) 2021.12.14
버튼(Flip-Flop) 함수 javaScript  (0) 2021.12.14
부트스트랩 버튼  (0) 2021.12.14