항해99

[2주차] [#03] Ajax 시작, 사용하기

Heoky 2022. 10. 4. 20:41

1. Ajax 뼈대

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

 


2. 예시 (미세먼지 open API 활용)

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

2-1. console 결과값

 


3. 특정 지역(도봉구)만 미세먼지 값 가져오기

$.ajax({
  type: "GET",
  url: "http://spartacodingclub.shop/sparta_api/seoulair",
  data: {},
  success: function(response){
		// 값 중 도봉구의 미세먼지 값만 가져와보기
		let dobong = response["RealtimeCityAir"]["row"][11];
		let gu_name = dobong['MSRSTE_NM'];
		let gu_mise = dobong['IDEX_MVL'];
		console.log(gu_name, gu_mise); // 도봉구 41
  }
})

 


4. 모든 구의 미세먼지 값을 찍어보기 (반복문 활용)

$.ajax({
    type: "GET", // GET 방식으로 요청한다.
    url: "http://spartacodingclub.shop/sparta_api/seoulair", // 요청할 open API 주소
    data: {}, // 요청 하면서 함께 줄 데이터 (GET 요청 시엔 비워두기)
    success: function (response) {
        // 모든 구의 미세먼지 값을 찍어보기
        let mise_list = response['RealtimeCityAir']['row'] // response.RealtimeCityAir.row

        for (let i = 0; i < mise_list.length; i++) {
            let mise = mise_list[i]
            let gu_name = mise['MSRSTE_NM'] // mise.MSRSTE_NM
            let gu_mise = mise['IDEX_MVL'] // mise.IDEX_MVL
            console.log(gu_name, gu_mise)
        }
    }
})