[Ajax] 간단한 예제 ( Hello Ajax ) JSP 기준
1. 클라이언트 소스 ( helloAjax.html )
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=euc-kr">
<title>Hello Ajax</title>
<script type="text/javascript">
var xhr = null;
function getXMLHttpRequest() {
if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP");//IE 상위 버젼
} catch (e1) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");//IE 하위 버젼
} catch (e2) {
return null;
}
}
} else if (window.XMLHttpRequest) {
return new XMLHttpRequest();//IE 이외의 브라우저(FireFox 등)
} else {
return null;
}
}// XMLHttpRequest 객체 얻기
function requestHello(URL) {
param = f.name.value;
URL = URL + "?name=" + encodeURIComponent(param);//한글 처리
xhr = getXMLHttpRequest();//XMLHttpRequest 객체 얻기
xhr.onreadystatechange = responseHello;//콜백 함수 등록
xhr.open("GET", URL, true);//연결
xhr.send(null);//전송
}// 서버에 요청
function responseHello() {
if (xhr.readyState == 4) {//완료
if (xhr.status == 200) {//오류없이 OK
var str = xhr.responseText;//서버에서 보낸 내용 받기
document.getElementById("message").innerHTML = str;//보여주기
} else {
alert("Fail : " + httpRequest.status);
}
}
}// 응답
</script>
</head>
<body>
<form name="f">
<input type="text" name="name">
<input type="button" value="입력" onclick="requestHello('hello.jsp')">
</form>
<div id="message"></div>
</body>
</html>
2. 서버 소스 ( hello.jsp )
<%@ page contentType="text/plain; charset=euc-kr" %>
<%
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
%>
안녕하세요, <%= name %> 회원님!
3. 홍길동이라고 입력하고 [입력] 버튼을 클릭하면 안녕하세요, 홍길동 회원님! 이라는 결과를 보인다.
[출처] [Ajax] 간단한 예제 ( Hello Ajax ) JSP 기준|작성자 메멘토