본문 바로가기
Ajax

AJAX-XMLHttpRequest 객체[AJAX개발]

by cellin 2023. 11. 2.

XMLHttpRequest 객체

XMLHttpRequest 객체는 웹 브라우저가 서버와 데이터를 교환할 때 사용

웹 브라우저가 백그라운드에서 계속해서 서버와 통신할 수 있는 것은 바로 이 객체를 사용하기 때문

 

 

 

 

XMLHttpRequest 객체의 생성

 

1. XMLHttpRequest 객체를 이용한 방법

2. ActiveXObject 객체를 이용한 방법

 

 

문법

# 익스플로러 7과 그 이상의 버전, 크롬, 파이어폭스, 사파리, 오페라에서는 XMLHttpRequest 객체를 사용 
var 변수이름 = new XMLHttpRequest();
 
# 스플로러의 구형 버전인 5와 6 버전에서는 ActiveXObject 객체를 사용
var 변수이름 = new ActiveXObject("Microsoft.XMLHTTP");
 

EXAMPLE

<!DOCTYPE html>
<html lang="ko">

<head>
	<meta charset="UTF-8">
	<title>Ajax XMLHttpRequest</title>
	<script>
		function sendRequest() {
			var httpRequest;
			function createRequest() {
				if (window.XMLHttpRequest) {	// 익스플로러 7 & 그 이상 버전, 크롬, 파이어폭스, 사파리, 오페라 등
					return new XMLHttpRequest();
				} else {						// 익스플로러 6 & 그 이하의 버전
					return new ActiveXObject("Microsoft.XMLHTTP");
				}
			}
			function receiveResponse() {
				// XMLHttpRequest 객체의 현재 상태가 요청 완료, 서버에 문서가 존재하면 받은 데이터 출력
				if (httpRequest.readyState == XMLHttpRequest.DONE && httpRequest.status == 200 ) {
					document.getElementById("text").innerHTML = httpRequest.responseText;
				}
			}
			httpRequest = createRequest();	// XMLHttpRequest 객체 생성
			httpRequest.onreadystatechange = receiveResponse;// XMLHttpRequest 객체의 현재 상태 파악
			// GET 방식의 비동기식 요청으로 Http 요청 생성
			httpRequest.open("GET", "/examples/media/ajax_intro_data.txt", true);
			httpRequest.send();			// Http 요청을 보냄
		}
	</script>
</head>

<body>

	<h1>XMLHttpRequest 객체 생성</h1>
	<button type="button" onclick="sendRequest()">Ajax 요청 보내기</button>
	<p id="text"></p>
	
</body>

</html>

**Ajax는 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신

 

 

 

 

 

 

 

사진: UnsplashClay Banks

 

728x90
반응형

'Ajax' 카테고리의 다른 글

서버로부터의 응답(response) 확인[AJAX개발]  (0) 2023.11.03
서버에 요청(request)하기[AJAX개발]  (0) 2023.11.03
AJAX-DOM, 노드, DOM API[AJAX]  (0) 2023.11.02
Ajax 란?  (0) 2023.11.02