bom's happy life

[웹 개발 2 주차] 개발일지 10 - Ajax 본문

Deveolpment Study🗂️/Javascript

[웹 개발 2 주차] 개발일지 10 - Ajax

bompeach 2022. 5. 30. 20:36

* Ajax는 jQuery를 임포트한 페이지에서만 동작 가능하다.

 

 

Ajax 기본 골격

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

 

 

Ajax 코드 해설

$.ajax({ type: "GET", // GET 방식으로 요청한다.

url: "http://spartacodingclub.shop/sparta_api/seoulair", (예시)

data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워둔다!)

success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음

console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성

}

})

 

 

모든 구의 미세먼지 값을 찍어보기

$.ajax({
    type: "GET",
    url: "http://spartacodingclub.shop/sparta_api/seoulair",
    data: {},
    success: function (response) {
        let mise_list = response["RealtimeCityAir"]["row"];
        for (let i = 0; i < mise_list.length; i++) {
            let mise = mise_list[i];
            let gu_name = mise["MSRSTE_NM"];
            let gu_mise = mise["IDEX_MVL"];
            console.log(gu_name, gu_mise);
        }
    }
});