반응형
SMALL
2021/02/09 - [개발/Javascript] - Ajax (Asyncronous Javascript and XML)
비동기 통신 방식
자바스크립트의 비동기 통신 방식은 여러 가지가 있다. (JQuery라이브러리를 사용하는 ajax 방식은 포함하지 않았다.)
- XMLHttpRequest(Web API)
- Promise(callback hell을 피하기 위해 자바스크립트에서 제공하는 객체)
- Fetch API (Promise 기반의 Web API)
- async/await(ES2017에서 추가된 자바스크립트 키워드)
2021/02/10 - [개발/Javascript] - Promise
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Hello</h1>
<input id="nameValue" type="text" name="name" />
<button id="btn" value="ajax">Ajax</button>
<div>
My name is
<span id="text"></span>
</div>
<script>
const xhr = new XMLHttpRequest();
const text = document.getElementById("text");
const btn = document.getElementById("btn");
const nameValue = document.getElementById("nameValue");
let status = xhr.status;
// =======================================================
//use xhr
btn.addEventListener("click", function () {
console.log("readyState : ", xhr.readyState);
let namev = nameValue.value;
let data = { name: namev };
data = JSON.stringify(data);
xhr.open("POST", "/name");
xhr.onreadystatechange = function () {
let status = xhr.status;
if (xhr.readyState === XMLHttpRequest.DONE) {
if (status === 0 || (status >= 200 && status < 400)) {
let result = JSON.parse(xhr.responseText);
text.innerHTML = result.name;
} else {
console.log("error responseText : ", xhr.responseText);
}
}
};
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(data);
});
// =======================================================
//usePromise
btn.addEventListener("click", function usePromise() {
return new Promise((resolve, reject) => {
let namev = nameValue.value;
let data = { name: namev };
data = JSON.stringify(data);
xhr.open("POST", "/name");
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState !== XMLHttpRequest.DONE) {
return;
}
if (status === 0 || (status >= 200 && status < 400)) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.status));
}
};
})
.then(JSON.parse)
.then((content) => {
text.innerHTML = content.name;
})
.catch(console.log);
});
// =======================================================
//usefetch
let useFetch = (url, method) => {
let namev = nameValue.value;
let data = { name: namev };
return fetch(url, {
method: method,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((data) => data.json())
.then((res) => (text.innerHTML = res.name))
.catch((error) => {
return console.log(new Error(error));
});
};
btn.addEventListener("click", function () {
useFetch("/name", "POST");
});
// =======================================================
//use async/await
let useAsync = async (url, method) => {
let namev = nameValue.value;
let data = {
method: method,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name: namev }),
};
const res = await fetch(url, data);
const resTxt = await res.json();
text.innerHTML = resTxt.name;
console.log(resTxt);
};
btn.addEventListener("click", function () {
useAsync("/name", "POST");
});
</script>
</body>
</html>
- fetch API는 반환값으로 Promise 객체를 반환한다.
- async/await 키워드도 반환값으로 Promise객체를 반환한다.
참고
developer.mozilla.org/ko/docs/Web/API/XMLHttpRequest
developer.mozilla.org/ko/docs/Web/API/Fetch_API/Fetch%EC%9D%98_%EC%82%AC%EC%9A%A9%EB%B2%95
developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/async_function#simple_example
반응형
LIST
'개발 > Javascript' 카테고리의 다른 글
arrow function (0) | 2021.02.21 |
---|---|
startsWith, endsWith, includes (0) | 2021.02.19 |
Promise (0) | 2021.02.10 |
Ajax (Asyncronous Javascript and XML) (0) | 2021.02.09 |
Event (0) | 2021.02.06 |