Javascript/개념정리

[공통] XHR Example

xowoony 2022. 11. 1. 14:52

학습일 : 2022. 11. 01
암기하세요


const xhr = new XMLHttpRequest(); 	// 객체화 
const formData = new FormData();	 // 요청시 같이 보낼 데이터
xhr.open('요청 방식', '요청 주소');
xhr.onreadystatechange = () => {
   if (xhr.readyState === XMLHttpRequest.DONE) { 		// XMLHttpRequest.DONE == 4임.어찌 되었든 끝난다면
         if (xhr.status >= 200 && xhr.status < 300) {		// 200이상 300미만 일 경우
			// 요청 성공 로직 구현
         } else {
			// 요청 실패 로직 구현
         }
     }
};
xhr.send(formData);

사용 예시

<!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>