[ajax] ajax 기본 골격/ 미세먼지 api를 이용하여 구 별 미세먼지 수치 출력해보기/70이상은 빨간색으로 바꾸기
2021. 6. 10. 12:04

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

script부분 함수를 실행할 부분에 넣는다


      
function q1() {
$('#names-q1').empty()
$.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 name = rows[i]['MSRSTE_NM']
let mise = rows[i]['IDEX_MVL']
let temp_html = ` <li>${name} : ${mise}</li>`
$('#names-q1').append(temp_html)
}
}
})
}

url부분에 우리가 가져올 오픈 api를 넣는다

가져온 응답은 response에 담아서 가져오게 된다.

이것은 미세먼지 api이다.

url에 들어가면 json형태로 값이 저장되어있다

이렇게 있는데 우리는 그 중에서 구이름과 미세먼지 수치만 가져올 것이다. 

 

변수를 하나 만들고 row안으로 들어간다

그리고 for문을 돌면서 구 이름과 미세먼지 수치를 가져와서

html을 append하여 붙이고 싶은 곳에 붙인다.

 

 

전체 코드

 


      
<!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;
}
</style>
<script>
function q1() {
$('#names-q1').empty()
$.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 name = rows[i]['MSRSTE_NM']
let mise = rows[i]['IDEX_MVL']
let temp_html = ` <li>${name} : ${mise}</li>`
$('#names-q1').append(temp_html)
}
}
})
}
</script>
</head>
<body>
<h1>jQuery+Ajax의 조합을 연습하자!</h1>
<hr />
<div class="question-box">
<h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
<p>모든 구의 미세먼지를 표기해주세요</p>
<p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
<button onclick="q1()">업데이트</button>
<ul id="names-q1">
<li>중구 : 82</li>
<li>종로구 : 87</li>
<li>용산구 : 84</li>
<li>은평구 : 82</li>
</ul>
</div>
</body>
</html>

그러면

업데이트를 눌렀을때

이렇게 쭉 나오게 된다.


그럼 여기서 70이상 수치를 가진 곳은 빨간색으로 표시해보자

 


      
function q1() {
$('#names-q1').empty()
$.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 name = rows[i]['MSRSTE_NM']
let mise = rows[i]['IDEX_MVL']
let temp_html = ``
if (mise<70){
temp_html = ` <li>${name} : ${mise}</li>`
}
else{
temp_html = ` <li class="bad">${name} : ${mise}</li>`
}
$('#names-q1').append(temp_html)
}
}
})
}

그러면 70이상인 곳에 class를 주어서 style을 바꿔주면 된다

 

728x90