JUST GO
[공통] XHR(XMLHttpRequest) 본문
XHR(XMLHttpRequest)
XMLHttpRequest(XHR)은 AJAX 요청을 생성하는 javaScript API 이다.
AJAX와 같이 페이지를 리프레쉬하지 않고서도 서버와 데이터를 받아오는 등의 인터랙션을 하기위해서 사용한다.
XHR 작성방법은 아래와 같다.
const xhr = new XMLHttpRequest();
xhr.open('요청 방식', '요청 주소');
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status >= 200 && xhr.status < 300) {
// 요청 성공 로직 구현
} else {
// 요청 실패 로직 구현
}
}
};
xhr.send(formData);
1 : OPENED
2
3
4 : "성공 | 실패"
- XHR example
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>XHR Example</title>
</head>
<body>
<input>
<br>
<b id="ipVal">IP 주소가 여기 표시됩니다.</b>
<br>
<button id="ipBtn">IP 주소 가져오기</button>
<script>
window.document.getElementById('ipBtn').addEventListener('click', () => {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.ipify.org');
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
ipBtn.removeAttribute('disabled');
if (xhr.status >= 200 && xhr.status < 300) {
window.document.getElementById('ipVal').innerText = xhr.responseText;
} else {
ipVal.innerText = '오류';
}
}
};
xhr.send();
ipVal.innerText = '잠시만 기다려 주세요.';
ipBtn.setAttribute('disabled', 'disabled');
});
</script>
</body>
</html>
- XHR 사용예시
Cover.show('인증번호를 전송하고 있습니다.\n잠시만 기다려 주세요.');
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('email', form['email'].value);
// 첫번째 email : @RequestParma(value="email")과 일치 해야함 // 두번째 email : input에 있는 name="email"과 일치해야함.
xhr.open('POST', './email');
// open -> 1 찍힘
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
// DONE -> 4 찍힘
Cover.hide();
if (xhr.status >= 200 && xhr.status < 300){
console.log(xhr.responseText);
// 상태 콘솔에 찍어줌
} else {
form.querySelector('[rel="emailWarning"]').innerText = '서버와 통신하지 못하였습니다. 잠시 후 다시 시도해주세요.'
form.querySelector('[rel="emailWarning"]').classList.add('visible');
}
}
};
xhr.send(formData);
'Spring Boot > 학습내용' 카테고리의 다른 글
[공통] 회원가입 페이지 (0) | 2022.11.03 |
---|---|
[공통] 이메일 인증 (0) | 2022.11.02 |
[기타] 유용한 사이트 (4) | 2022.10.31 |
[공통] 의존성 추가 (0) | 2022.10.31 |
[공통] 프로젝트 생성 (0) | 2022.10.31 |