- 크롬 개발자 도구에 다음과 같이 써보세요
👉참고! Ajax는 jQuery를 임포트한 페이지에서만 동작 가능합니다.
즉, http://google.com/ 과 같은 화면에서 개발자도구를 열면,
jQuery가 임포트 되어있지 않기 때문에 아래와 같은 에러가 뜹니다.
Uncaught TypeError: $.ajax is not a function
→ ajax라는 게 없다는 뜻
👉JQuery가 들어간 페이지 여기서 콘솔창 띄우기 Ajax작동: O
http://localhost:63342/frontend/index_JQuery%EC%A0%81%EC%9A%A9.html?_ijt=rvvd0fe2pcb1k6bsal86jcpn9s&_ij_reload=RELOAD_ON_SAVE
여기서 콘솔창 띄우기 콘솔창에서 Ajax가 작동
👉JQuery가 없는 페이지 여기서 콘솔창 띄우기 Ajax작동: X
http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99
Ajax 기본골격 및 코드 해설
$.ajax({ type: "GET", // GET 방식으로 요청한다.
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
}
})
- $ajax 코드 설명
- type: "GET" → GET 방식으로 요청한다.
- url: 요청할 url
- data: 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
👉리마인드 GET 요청은, url뒤에 아래와 같이 붙여서 데이터를 가져갑니다.
http://naver.com?param=value¶m2=value2
POST 요청은, data : {} 에 넣어서 데이터를 가져갑니다.
data: { param: 'value', param2: 'value2' },
- success: 성공하면, response 값에 서버의 결과 값을 담아서 함수를 실행한다.
👉 결과가 어떻게 response에 들어가나요? → 받아 들이셔야 합니다..!
(대부분의 개발자들도 내부 원리는 코드를 안 뜯어봐서 몰라요.^^;;)
success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
console.log(response) //서버에서 준 결과를 이용해서 나머지 코드를 작성
}
콘솔창에 붙어넣기 하고
여기에URL을입력을 ↓미세먼지 openAPI 링크 붙어넣기
http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99
미세먼지openAPI에 값이 response에 저장됨
여기서 가져다가 값 쓰기
Ajax 통신의 결과값을 이용해보기
- 개발자도구 콘솔에 찍어보기
$.ajax({
type: "GET", // GET 방식으로 요청한다.
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
console.log(response ['RealtimeCityAir']['row'][0]) }
}
})
- 개발자도구 콘솔에 찍어보기
$.ajax({
type: "GET", // GET 방식으로 요청한다.
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
success: function(response){ // 값 중 도봉구의 미세먼지 값만 가져와보기
let rows = response ['RealtimeCityAir']['row']
for (let i = 0; i <rows.length; i++) {
let gu_name = rows[i]['MSRSTE_NM']
let gu_mise = rows[i]['IDEX_MVL']
console.log(gu_name,gu_mise)
}
})
- 모든 구의 미세먼지 값을 찍어보기
$.ajax({
type: "GET",
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {},
success: function(response){
let rows = response ['RealtimeCityAir']['row']
for (let i = 0; i <rows.length; i++) {
let gu_name = rows[i]['MSRSTE_NM']
let gu_mise = rows[i]['IDEX_MVL']
if (gu_mise < 70) {
console.log(gu_name,gu_mise)
}
}
});