AJAX란 비동기 JavaScript와 XML을 의미한다. 서버측과 다양한 형식(JSON, XML, HTML 및 일반 txt)의 정보를 주고 받을 수 있으며, AJAX의 특징은 페이지 전체를 새로고침하지 않더라도 최신 정보를 얻어내는 "비동기성"이다. 이러한 비동시성을 통해, 사용자 Event에 따라 일부분만을 업데이트할 수 있다.
document.addEventListener('DOMContentLoaded',function(){
alert("function called");
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://spartacodingclub.shop/sparta_api/weather/seoul', true);
xhr.responseType='json';
xhr.send();
xhr.onload = function(){
if(xhr.status == 200){
alert("API is availabe");
let tmp = document.querySelector('#title_temp');
let city = xhr.response['city'];
let temp = xhr.response['temp'];
let msg = city + ' , ' + temp;
while(tmp.firstChild){
tmp.removeChild(tmp.firstChild);
}
tmp.append(msg);
}
else{
alert("API is not available");
}
}
})
위 코드는 XHR을 활용한 예제로, API에서 서울의 날씨를 받아오는 함수이다. 위 코드를 조금씩 뜯어보면 다음과 같다.
document.addEventListener('DOMContentLoaded',function(){
alert("function called");
...
})
document의 상태가 'DOMContentLoaded'일 때, function을 호출한다. 이때 함수가 정상적으로 호출된 경우, "function called"라는 메세지가 출력된다.
EventTarget.addEventListener(type, listener, option)
var xhr = new XMLHttpRequest(); // 생성자
xhr.open('GET', 'http://spartacodingclub.shop/sparta_api/weather/seoul', true);
xhr.responseType='json';
xhr.send();
xhr.onload = function(){
if(xhr.status == 200){
alert("API is availabe");
}
else{
alert("API is not available");
}
while(tmp.firstChild){
tmp.removeChild(tmp.firstChild);
}
// 1) DOM 트리 구성 확인
$(document).ready(function() {
// 여기에 코드를 입력하세요
$.ajax({
// 2) XMLHttpRequest(): 생성 및 정보 받아오기
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
data: {},
// 3) XMLHttpRequest(): 오류 검증
success: function(response) {
$('#title_temp').empty();
let tmp = '';
let city = response['city'];
let temp = response['temp'];
tmp = `${city} , ${temp}도`
$('#title_temp').append(tmp);
}
})
});
jQuery와 AJAX를 활용하면 이처럼 간단하게 코드를 줄일 수 있다.