웹 개발/웹개발종합
웹 개발 기초 4 - Ajax
개발자명백
2023. 2. 28. 17:22
0. Ajax란?
Asynchronous JavaSccript and XML의 약자로서 Javascript를 사용한 비동기 통신입니다. 클라이언트와 서버간 JSON, XML, HTML, TEXT 등의 데이터를 주고 받을 수 있습니다. Ajax 프레임워크로는 Prototype, script.aculo.us, dojo, jQuery 등이 있습니다. (http://www.tcpschool.com/ajax/intro)
Ajax를 이용한 웹 응용 프로그램은 자바스크립트 코드를 통해 웹 서버와 통신합니다. 따라서 사용자의 동작에 영향을 주지 않으면서 백그라운드에서 지속적으로 서버와 통신할 수 있습니다. 그 외 특징으로는 다음과 같습니다.
웹 페이지 전체를 로딩하지 않고 일부만을 갱신할 수 있다.
웹 페이지가 로드된 후 서버로 요청 할 수 있다.
웹 페이지가 로드된 후 서보로 응답 받을 수 있다.
백그라운드 영역에서 서버로 데이터를 보낼 수 있다.
클라이언트-서버 간 풀링 방식으로서 푸쉬 방식의 실시간 서비스를 만들 수 없다.
바이너리 데이터를 보내거나 받을 수 없다.
Ajax 스크립트가 포함되지 않은 서버에 Ajax 요청을 보낼 수 없다.
클라이언트 PC로 Ajax 요청을 보낼 수 없다.
1. ajax 연습하기 - 1
<!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>
<title>미세먼지 GET 요청하기</title>
<style>
.good {
color: green;
}
.normal {
color: yellow;
}
.bad {
color: red;
}
.very-bad {
color: purple;
}
.wrong{
color: white;
}
</style>
<script>
function update_mise() {
alert("미세먼지 수치를 업데이트 합니다.");
$('#seoul-mise').empty();
let ajax = $.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {},
success: function (response) {
let page = $('#seoul-mise');
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 <= 30 & gu_mise >= 0) {
page.append(`<li class="good">${gu_name} ${gu_mise}</li>`);
} else if (gu_mise <= 80 & gu_mise > 30) {
page.append(`<li class="normal">${gu_name} ${gu_mise}</li>`);
} else if (gu_mise <= 150 & gu_mise > 80) {
page.append(`<li class="bad">${gu_name} ${gu_mise}</li>`);
} else if (gu_mise > 150) {
page.append(`<li class="very-bad">${gu_name} ${gu_mise}</li>`);
} else {
page.append(`<li class="wrong">${gu_name} ${gu_mise}</li>`);
}
}
}
});
}
</script>
</head>
<body>
<h1>JQuery + Ajax 연습하기</h1>
<hr>
<h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
<p>모든 구의 미세먼지를 표기하기, 업데이트를 누를 때마다 지웠다 새로 쓰기</p>
<button id="update-mise" onclick="update_mise()">업데이트</button>
<ul id="seoul-mise">
</ul>
</body>
</html>
2. ajax 연습하기 - 2
<!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;
}
table {
border: 1px solid;
border-collapse: collapse;
}
td,
th {
padding: 10px;
border: 1px solid;
}
.urgent{
color: red;
}
</style>
<script>
function q1() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulbike",
data: {},
success: function (response) {
let tbody = $('#names-q1');
tbody.empty();
let info_list = response['getStationList']['row'];
for (let i = 0; i < info_list.length; i++) {
let info = info_list[i];
let stationName = info['stationName'];
let rackTotCnt = info['rackTotCnt'];
let parkingBikeTotCnt = info['parkingBikeTotCnt'];
if (parkingBikeTotCnt < 5) {
tbody.append(`<tr class="urgent"><td>${stationName}</td><td>${rackTotCnt}</td><td>${parkingBikeTotCnt}</td></tr>`);
} else {
tbody.append(`<tr><td>${stationName}</td><td>${rackTotCnt}</td><td>${parkingBikeTotCnt}</td></tr>`);
}
}
}
});
}
</script>
</head>
<body>
<h1>jQuery + Ajax의 조합을 연습하자!</h1>
<hr/>
<div class="question-box">
<h2>2. 서울시 OpenAPI(실시간 따릉기 현황)를 이용하기</h2>
<p>모든 위치의 따릉이 현황을 보여주세요</p>
<p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
<button onclick="q1()">업데이트</button>
<table>
<thead>
<tr>
<td>거치대 위치</td>
<td>거치대 수</td>
<td>현재 거치된 따릉이 수</td>
</tr>
</thead>
<tbody id="names-q1">
<tr>
<td>102. 망원역 1번출구 앞</td>
<td>22</td>
<td>0</td>
</tr>
<tr>
<td>103. 망원역 2번출구 앞</td>
<td>16</td>
<td>0</td>
</tr>
<tr>
<td>104. 합정역 1번출구 앞</td>
<td>16</td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
3. ajax 연습하기 - 3
<!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;
}
div.question-box > div {
margin-top: 30px;
}
</style>
<script>
function q1() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rtan",
data: {},
success: function (response) {
$('#img-rtan').attr("src", `${response['url']}`);
$('#text-rtan').text(`${response['msg']}`);
}
});
}
</script>
</head>
<body>
<h1>JQuery+Ajax의 조합을 연습하자!</h1>
<hr/>
<div class="question-box">
<h2>3. 르탄이 API를 이용하기!</h2>
<p>아래를 르탄이 사진으로 바꿔주세요</p>
<p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
<button onclick="q1()">르탄이 나와</button>
<div>
<img id="img-rtan" src="http://spartacodingclub.shop/static/images/rtans/SpartaIcon11.png" width="300"/>
<h1 id="text-rtan">나는 ㅇㅇㅇ하는 르탄이!</h1>
</div>
</div>
</body>
</html>
4. ajax 연습하기 - 4
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>오늘의 날씨</title>
<style>
div {
display: flex;
flex-direction: row;
}
</style>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
data: {},
success: function (response) {
console.log(response);
$('#weather-tmpr').text(`${response['temp']}`);
$('#weather-icon').attr('src', `${response['icon']}`);
}
})
});
</script>
</head>
<body>
<h1>오늘 서울의 날씨를 출력합니다.</h1>
<hr>
<div>
<p>현재 기온 : <span id="weather-tmpr">0.00도</span></p>
<img id="weather-icon" src="">
</div>
</body>
</html>