두 소프트웨어 구성 요소가(클라이언트 / 서버) 서로 통신할 수 있게 하는 메커니즘
서버와 통신하기 위해
[XMLHttpRequest](https://developer.mozilla.org/ko/docs/Web/API/XMLHttpRequest)객체를 사용 — MDN
// http://spartacodingclub.shop/sparta_api/seoulair
// ! Ajax는 jQuery를 임포트한 페이지에서만 동작 가능!
<script>
$.ajax({
type: 'GET', // Get방식으로
url: 'http://spartacodingclub.shop/sparta_api/seoulair',
data: {},
success: function (response) {
let rows = response['RealtimeCityAir']['row']; // response(=RealtimeCityAir)를 찍어주게삳ㅇ!
for (let i = 0; i < rows.length; i++) {
let gu_name = rows[i]['MSRSTE_NM'];
let gu_mise = rows[i]['IDEX_NM'];
console.log(gu_name, gu_mise);
}
},
});
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<!-- jQuery를 import 합니다 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Style -->
<style type="text/css">
div.question-box {
margin: 10px 0 20px 0;
}
.bad {
color: red;
}
.normal {
color: orange;
}
.good {
color: cornflowerblue;
}
</style>
<!-- Script -->
<script>
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_miseN = rows[i]['IDEX_MVL'];
let gu_mise = rows[i]['IDEX_NM'];
let temp_html = ``;
if (gu_miseN <= 60) {
temp_html = `<li class = "good">${gu_name} : ${gu_miseN} | ${gu_mise}</li>`;
} else if(gu_miseN <= 120) {
temp_html = `<li class = "normal">${gu_name} : ${gu_miseN} | ${gu_mise}</li>`;
} else if (gu_miseN > 120 ){
temp_html = `<li class = "bad">${gu_name} : ${gu_miseN} | ${gu_mise}</li>`;
}
$('#names-q1').append(temp_html);
}
},
});
}
</script>
<title>ajax 연습</title>
</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"></ul>
</div>
</body>
</html>