javascript와 서버

jinkyung·2021년 2월 4일
0

Ajax

목록 보기
3/8

js를 이용하여 언제든지 서버에 데이터를 요청하고 받아올 수 있다.
굳이 jsp 페이지를 통하지 않아도 된다.

get_XMLHttpRequest.html
: 4, 200 -> 정상적으로 수신되었다는 뜻
비동기 -> 결과를 나중에 콜백함수로 통보받겠다

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	function reqList(){
		var xhr = new XMLHttpRequest();
		//데이터가 수신되면 호출된 callback함수 등록 
		xhr.onreadystatechange = function(){
			//0=초기화, 1=로딩중, 2=로딩됨, 3=대화상태, 4=전송완료 
			if(xhr.readyState == 4){
			// 200=에러없음, 404=페이지가 존재하지 않음, ...
				if(xhr.status == 200){
					var data = xhr.responseText;
					console.log(data);
					document.getElementById("resp").innerHTML = data;
				}
			}
		};
		
		//이 주소로 get요청을 할 것이다. 
		//메서드, 주소, 비동기 = true, 동기 = false
		xhr.open("GET", "/Contact/list.do", true);
		xhr.send();
	}
	function delList(){
		document.getElementById("resp").innerHTML="";
	}
</script>
</head>
<body>
	<button type="button" onclick="reqList();">요청</button>
	<button type="button" onclick="delList();">삭제</button>
	<p id="resp"></p>
</body>
</html>

결과


02.post_XMLHttpRequest.html

: 한글은 반드시 encodeURIComponent를 사용해야한다.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	function reqList(){
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4){
				if(xhr.status == 200){
					var data = xhr.responseText;
					console.log(data);
					document.getElementById("resp").innerHTML = data;
				}
			}
		}
		xhr.open("POST", "/Contact/add.do", true);
		xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		var name = encodeURIComponent("유시진");
		var tel = encodeURIComponent("010-0987-6543");
		var address = encodeURIComponent("우르크");
		var reqStr = "name="+name+"&tel="+tel+"&address="+address;
		console.log("send:"+reqStr);
		xhr.send(reqStr);
	}
	function delList(){
		document.getElementById("resp").innerHTML = "";
	}
</script>
</head>
<body>
	<button type="button" onclick="reqList();">요청</button>
	<button type="button" onclick="delList();">삭제</button>
	<p id="resp"></p>
</body>
</html>

결과

0개의 댓글

관련 채용 정보