API를 통해서 클라이언트 - 서버 통신.
GET 방식 으로 데이터를 전달하는 방법
예시) google.com/search?q=아이폰&sourceid=chrome&ie=UTF-8
위 주소는 google.com의 search 창구에 다음 정보를 전달합니다!
q=아이폰 (검색어)
sourceid=chrome (브라우저 정보)
ie=UTF-8 (인코딩 정보)
미세먼지 OpenAPI 받아오기 (데이터가 Json 형태로 되어있음)
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
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']
console.log(gu_name, gu_mise)
}
}
})
ajax를 통해서 url을 입력하면 response로 값을 return 해 준다.
이때 내가 원하는 부분만 가져와서 rows 값에 넣으면
위 그림과 같이 구 별 미세먼지 값을 console에서 확인할 수 있다.
해당 값을 페이지 내에서 가져오고 싶으면?
-> console.log 값이 아닌 백틱 (`)을 이용해서 가져올 수 있다!
function q1() {
$('#names-q1').empty()
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
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']
let temp_html = ''
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)
}
}
})
}
mise 값이 50이 넘으면 빨간색, 아니면 검은색으로 가져오게 만드는 function 로직 설정. q1은 onclick에 넣어둔다.
Update 버튼을 클릭할 때 마다 구 별 미세먼지 값을 가져오는데 50이 넘는 경우엔 빨간색으로 가져온다.
뿐만 아니라 img와 text도 바꿀 수 있다.
img 바꾸는 법 : $(id값).attr("src", url)
ex. $('#img-rtan').attr("src", response.url)
text 바꾸는 법 : $(id값).text(text)
ex. $('#text-rtan').text(response.msg)