Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

미래학자

[HTTP Ajax요청] XMLHttpRequest(XHR), fetch API 사용하기 본문

HTML, CSS

[HTTP Ajax요청] XMLHttpRequest(XHR), fetch API 사용하기

미래학자 2018. 3. 25. 11:25

이번에는 Ajax에 대해 정리해보려 합니다. Ajax는 Asynchronous Javascript And Xml의 약자로, 웹 클라이언트(브라우저 같은)에서 웹서버와 비동기적으로 데이터를 교환하는 방법입니다. 웹 개발하면서 필수적으로 사용하는 기술이기 때문에 jQuery같은 라이브러리에는 Ajax요청 모듈이 내장되어 있습니다.

직접 Ajax요청을 하는 것이 어렵지 않기 때문에 XMLHttpRequest객체를 이용한 Ajax요청을 직접 해보겠습니다. 그리고 fetch API를 사용하여 요청 보내는 것도 해보겠습니다.

먼저 XMLHttpRequest 예제를 봅시다.



<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>drag and drop</title>
</head>
<body>
<div style="size:25pt;" id="ajax_btn">샘플 요청하기</div>
</body>
<script>
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
console.log(xhr.readyState);
if (xhr.readyState === XMLHttpRequest.DONE) {
if(xhr.status === 200 || xhr.status === 201) {
console.log(xhr.responseText);
} else {
console.error(xhr.responseText);
}
}
};
const button = document.getElementById('ajax_btn');
button.onclick = e => {
xhr.open('GET', 'http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo');
xhr.send(null);
}
</script>
</html>


onreadystatechange 함수는 함수이름에서 알 수 있듯이 xhr 요청의 상태가 바뀔때마다 발생하는 함수 입니다.

xhr의 상태는 다음과 같습니다. 이해하기 쉽게도 처음 상태 UNSENT에서 순차적으로 단계가 진행되면서 DONE까지 갑니다.


 상태

UNSENT 

OPENED 

HEADER_RECEIVED 

LOADING 

DONE 

 값

 0

1

2

3

4



간략히 요약해보면, xhr 요청을 하고 readyState가 계속해서 진행하면서 변경이되고, 이때 변경되는 상태값에서 DONE일 때 요청이 마무리가 됐으니

이때 로직을 처리하는 방식입니다.


이것보다 더 간단하고 직관적인 방법이 fetch API입니다. 이 fetch API는 정말 기분좋게도 현재 IE브라우저에서는 사용하지 못합니다. 그럼 더더욱 fetch API를 사용해야 되겠네요

fetch API사용 코드 입니다.


GET


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>drag and drop</title>
</head>
<body>
<div style="size:25pt;" id="ajax_btn">샘플 요청하기</div>
</body>
<script>
const button = document.getElementById('ajax_btn');
button.onclick = e => {
fetch('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo').then((res) => {
if (res.status === 200 || res.staus === 201) {
res.text().then(text => console.log(text));
} else {
console.error(res.statusText);
}
}).catch(err => console.error(err));
}
</script>
</html>
</script>
</html>



코드를 보면 fetch 함수가 호출이 되고 then, catch 로 결과를 처리하는데 이는 es2015에서 새롭게 추가된 Promise를 사용하여 처리한 것입니다.

외부로 무언가 요청을 하면 응답을 받기 까지 시간이 걸리게 됩니다. promise를 사용하면 요청을 하고 응답을 받은 후 then을 실행합니다. 그렇기 때문에 위 XHR를 사용했을 때 처럼

결과를 받은 상태(DONE)에서 로직을 바로 처리할 수 있습니다. 정말 편하죠?? 아래에서는 POST요청을 보겠습니다.


POST



<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>drag and drop</title>
</head>
<body>
<div style="size:25pt;" id="ajax_btn">fetch POST</div>
</body>
<script>
const button = document.getElementById('ajax_btn');
button.onclick = e => {
const data = { name: 'test' };
const headers = new Headers();
fetch('https://sample.com/post', {
method: 'POST',
data,
headers,
}).then((res) => {
if (res.status === 200 || res.status === 201) {
res.json().then(json => console.log(json));
} else {
console.error(res.statusText);
}
}).catch(err => console.error(err));
}
</script>
</html>
</script>
</html>


post 요청도 크게 다르지 않습니다. fetch에 두번째 파라미터는 옵션값 입니다.

Comments