2021 프론트 엔드 로드맵 따라가기/JS
XHR object를 이용한 비동기 통신
알 수 없는 사용자
2021. 6. 7. 00:55
xhr.open()
요청 타입 및 요청 대상의 URL 또는 파일이름을 상세하여 초기화시키는 메서드이다. 세번째 파라미터는 비동기 여부이다.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open
XMLHttpRequest.open() - Web APIs | MDN
The XMLHttpRequest method open() initializes a newly-created request, or re-initializes an existing one.
developer.mozilla.org
xhr.onload
요청한 데이터를 받았을 때 실행될 함수를 담는 프로퍼티이다.
*참고: HTTP 상태코드 https://developer.mozilla.org/ko/docs/Web/HTTP/Status
HTTP 상태 코드 - HTTP | MDN
HTTP 응답 상태 코드는 특정 HTTP 요청이 성공적으로 완료되었는지 알려줍니다. 응답은 5개의 그룹으로 나누어집니다: 정보를 제공하는 응답, 성공적인 응답, 리다이렉트, 클라이언트 에러, 그리고
developer.mozilla.org
xhr.send()
설정된 값을 기반으로 요청을 보낸다.
xhr.onreadystatechange
해당 프로퍼티에 할당된 함수가 readystate가 바뀔 때마다 호출된다.
document.querySelector("#button").addEventListener("click", loadData);
function loadData (e) {
// Create an XHR Object
const xhr = new XMLHttpRequest();
console.log("READYSTATE", xhr.readyState); // 0
// Open
xhr.open("GET", "data.txt", true);
console.log("READYSTATE", xhr.readyState); // 1
// Optional - Used for spinners / loaders
xhr.onprogress = function () {
console.log("READYSTATE", xhr.readyState); // 3
}
xhr.onload = function () { // at this point, readyState is 4
if (this.status === 200) {
// console.log(this.responseText);
document.querySelector("#output").innerHTML = `<h1>${this.responseText}</h1>`;
}
}
// it's older syntax
// xhr.onreadystatechange = function () {
// console.log("READYSTATE", xhr.readyState);
// if (this.status === 200 && this.readyState === 4) {
// console.log(this.responseText);
// }
// }
xhr.onerror = function () {
console.log("Request error...");
}
xhr.send();
// readyState Values
// 0: request not initialized
// 1: server connection established
// 2: request received
// 3: processing request
// 4: request finished and response is ready
// HTTP Statuses
// 200: OK
// 403: "Forbidden"
// 404: "Not Found"
};