KIC/JSP

day46_2 - JSP(AJAX)

바차 2021. 8. 20. 00:36
반응형

[AJAX]

- AJAX를 사용하면 장면 뒤에서 웹 서버와 데이터를 교환하여 웹 페이지를 비동기 적으로 업데이트 할 수 있다.

 

- 전체 페이지를 다시 로드하지 않고도 웹 페이지의 일부를 업데이트 할 수 있다.

 

 

 

[AJAX 작동 방식]

 

1. 웹 페이지에서 이벤트가 발생 (페이지가 로드되고 버튼이 클릭 됨)

 

2. XMLHttpRequest 객체는 JavaScript에 의해 생성

 

3. XMLHttpRequest 객체는 웹 서버에 요청을 보낸다.

 

4. 서버가 요청을 처리

 

5. 서버가 웹 페이지에 응답을 보낸다.

 

6. 응답은 JavaScript에 의해 읽혀진다.

 

7. 적절한 조치(EX: 페이지 업데이트) 가 JavaScript 에 의해 수행

'

 

 

[AJAX Property]

- AJAX가 잘 수행되었을 경우 readyState가 4번이고, status가 200인 경우이다.

 

 

 

[AJAX 예제1]

test01.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<body>
<table>
<tr> <td><font color="red"> sample jsp </font></td></tr>
<tr> <td><font color="blue"> sample jsp </font></td></tr>
<tr> <td><font color="yellow"> sample jsp </font></td></tr>

</table>
</body>
</html>

 

ajax01.html

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<body>
<table>
<tr> <td><font color="red"> sample jsp </font></td></tr>
<tr> <td><font color="blue"> sample jsp </font></td></tr>
<tr> <td><font color="yellow"> sample jsp </font></td></tr>

</table>
</body>
</html>

 

 

 

[AJAX 예제2]

test02.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>


<table>
<% request.setCharacterEncoding("UTF-8"); %>
<tr> <td><%=request.getParameter("name") %></td></tr>
<tr> <td><font color="red"> sample jsp </font></td></tr>
<tr> <td><font color="blue"> sample jsp </font></td></tr>
<tr> <td><font color="yellow"> sample jsp </font></td></tr>

</table>

 

 

ajax02.html

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>AJAX2</title>
</head>
<body>
<form name="f" method="post">
<input type="text" name="name">
<input type="button" value="입력" onclick="helloServer()">
<div id="demo"></div>

</form>

<script>
function helloServer(){
	const xhttp = new XMLHttpRequest()
	const parms = "?name=" + encodeURIComponent(document.f.name.value)
	
	
	xhttp.open("GET", "test02.jsp" + parms, true)/*test01과 같은 경로 안에 있기 때문에 상대 경로로 작성 함  */
	xhttp.send()
	
	
	xhttp.onreadystatechange = callBack

}

function callBack(){
	if(this.readyState == 4 && this.status == 200){
		alert(this.responseText)
	document.getElementById("demo").innerHTML = this.responseText
	}
}
</script>
</body>
</html>

가나다 입력

 

 

300x250