우리는 보통 데이터를 페이지에 띄울 때
get과post를 사용한다.
get : 통상적으로 데이터 조회를 요청할 때
post : 통상적으로 데이터 생성,변경,삭제를 요청할 때
이번 시간에는 get을 활용했다.
get을 사용한 코드는 다음과 같다
$.ajax({
type: "GET",
url: "", -> 데이터url
data: {},
success: function (response) {
// 구현할 기능
})
서울시 데이터를 활용해서 현재 미세먼지 농도 출력하고
미세먼지 농도 100 이상인 지역 빨간색으로 표기해주기 ▼
// 빨간색 표기
<style>
.bad{
color:red;
}
</style>
// 스크립트 문 ajax+jquery 조합
<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_mise = rows[i]['IDEX_MVL']
let temp_html = ``
if(gu_mise > 100){
temp_html = `<li class="bad">${gu_name} : ${gu_mise}</li>`
} else{
temp_html = `<li>${gu_name} : ${gu_mise}</li>`
}
$('#names-q1').append(temp_html)
}
}
})
}
</script>
// html문
<button onclick="q1()">업데이트</button>
<ul id="names-q1"></ul>
for문을 활용하여 데이터를 변수에 저장해놓고, jquery를 통해서 출력해 봤는데 걱정했던것 보다는 간단했다.
업데이트 버튼을 누를 때 마다 이미지와 텍스트가 바뀌게 하기 ▼
// 스크립트문 ajax+jquery조합(attr, text 사용)
<script>
function q1() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rtan",
data: {},
success: function (response) {
let url = response['url']
let msg = response['msg']
$('#img-rtan').attr('src',url)
$('#text-rtan').text(msg)
}
})
}
</script>
// html문
<button onclick="q1()">르탄이 나와</button>
<div>
<img id="img-rtan" width="300" src="http://spartacodingclub.shop/static/images/rtans/SpartaIcon11.png"/>
<h1 id="text-rtan">나는 ㅇㅇㅇ하는 르탄이!</h1>
</div>
jquery 문법 중 attr을 이용해서 이미지를 바꾸고, text를 이용해서 글자를 변경해 봤다.
버튼을 누를때마다 데이터를 가져와서 이미지,텍스트르 변경해주는게 신기하고 유용하게 사용할 수 있을 것 같다.
페이지 로딩 직후 실행하기 ▼
<script>
$(document).ready(function () {})
</script>
{} 안에 실행하고싶은 내용을 ajax+jquery조합으로 써내려가면 된다.
서울시 현재 기온을 출력하는 것을 연습해 봤다.
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
data: {},
success: function (response) {
let seoul_temp = response['temp']
$('#temp').text(seoul_temp)
}
})
});
</script>
위에 jquery의 text를 이용해서 실시간 서울 기온을 받아오는 방법이다.
ajax+jquery 조합을 해봤는데, 어려울거라 생각했지만 형식은 거의 같고
변수에 어떤 값을 넣어줄 것인지? 그 변수를 어떻게 보여줄 것인지에 대해서만 잘 생각해본다면 정말 쉽게 구현할 수 있는 기능인것 같다.