๐Ÿ’ป

JavaScript ์˜ ์ดํ•ด - [AJAX] XHR(XMLHttpRequest) ๋ณธ๋ฌธ

KITRI/JAVASCRIPT

JavaScript ์˜ ์ดํ•ด - [AJAX] XHR(XMLHttpRequest)

๋˜ํšจ๋‹ˆ 2020. 7. 16. 10:36

XHR(XMLHttpRequest)์ด๋ž€?

 

XMLHttpRequest(XHR)์€ AJAX ์š”์ฒญ์„ ์ƒ์„ฑํ•˜๋Š” JavaScript API์ž…๋‹ˆ๋‹ค. XHR์˜ ๋ฉ”์„œ๋“œ๋กœ ๋ธŒ๋ผ์šฐ์ €์™€ ์„œ๋ฒ„๊ฐ„์˜ ๋„คํŠธ์›Œํฌ ์š”์ฒญ์„ ์ „์†กํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

XMLHttpRequest(XHR) ๊ฐ์ฒด๋Š” ์„œ๋ฒ„์™€ ์ƒํ˜ธ ์ž‘์šฉํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. ์ „์ฒด ํŽ˜์ด์ง€๋ฅผ ์ƒˆ๋กœ ๊ณ ์น˜์ง€ ์•Š๊ณ ๋„ URL์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฒ€์ƒ‰ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋ฅผ ํ†ตํ•ด ์›น ํŽ˜์ด์ง€๋Š” ์‚ฌ์šฉ์ž์˜ ์ž‘์—…์„ ๋ฐฉํ•ดํ•˜์ง€ ์•Š๊ณ  ํŽ˜์ด์ง€์˜ ์ผ๋ถ€๋งŒ ์—…๋ฐ์ดํŠธ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. AJAX ํ”„๋กœ๊ทธ๋ž˜๋ฐ์— XMLHttpRequest๋งŽ์ด ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

 

 

[์ฐธ๊ณ ์ž๋ฃŒ์ถ”๊ฐ€]

https://www.w3schools.com/js/js_ajax_http.asp

 

AJAX The XMLHttpRequest Object

AJAX - The XMLHttpRequest Object The keystone of AJAX is the XMLHttpRequest object. The XMLHttpRequest Object All modern browsers support the XMLHttpRequest object. The XMLHttpRequest object can be used to exchange data with a web server behind the scenes.

www.w3schools.com


command.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
${param.msg}

 

postXHR.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="postXHR.js"></script>
</head>
<body>
	<form id="createForm" action="">
		<input type="text" name="msg"/>
		<input type="button" value="์ž…๋ ฅ" onclick="toServer()"/>
	</form>
	<br /><br />
	
	<div id="disp">
		
	</div>
</body>
</html>

 

postXHR.js

/**
 * 
 */

var xhr = null;
var arr = new Array();

function toServer(){
	var msg = document.getElementById("createForm").msg.value;
	if(window.XMLHttpRequest){
		xhr = new XMLHttpRequest;
	}else{
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
//	GET
//	xhr.open("GET", "command.jsp?msg=" + msg, true); //์š”์ฒญ๋ฐฉ์‹, ์„œ๋ฒ„ํŒŒ์ผ, ๋น„๋™๊ธฐ์‹(์ •์ ํŽ˜์ด์ง€)
//	xhr.send();
	
//	POST
	xhr.open("POST", "command.jsp", true);
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr.send("msg="+msg);
	xhr.onreadystatechange = process;
}	
function process(){
	if(xhr.readyState==4 && xhr.status==200){
		arr.push("msg" + xhr.responseText);
		
		var disp = document.getElementById("disp");
		disp.innerText = xhr.responseText;
	}
	
	//alert(arr.join("\n"));
}

 

๋ฐ˜์‘ํ˜•
Comments