Ajax

[Ajax] Ajax 간단한 예제 (helloAjax.html)

MorningPhys 2015. 7. 9. 11:38

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 request = null;
 
function getXMLHttpRequest() {
    if (window.ActiveXObject) {
        try {
            // IE 상위 버젼
            return new ActiveXObject("Msxml2.XMLHTTP");
 
        } catch (e1) {
            try {
                // IE 하위 버젼
                return new ActiveXObject("Microsoft.XMLHTTP");
 
            } catch (e2) {
                return null;
            }
        }
    } else if (window.XMLHttpRequest) {
        // IE 이외의 브라우저(FireFox 등)
        return new XMLHttpRequest();
 
    } else {
        return null;
    }
} // XMLHttpRequest 객체 얻기
 
 
 
function requestHello(URL) {
    param = f.name.value;
    URL = URL + "?name=" + encodeURIComponent(param); // 한글 처리
    request = getXMLHttpRequest(); // XMLHttpRequest 객체 얻기
    request.onreadystatechange = responseHello; // 콜백 함수  등록
    request.open("GET", URL, true); // 연결
    request.send(null); //전송
} // 서버에 요청
 
 
 
function responseHello() {
    if (request.readyState == 4) { // 완료
        if (request.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. 결과 화면

홍길동이라고 입력하고 [입력] 버튼을 클릭하면

"안녕하세요, 홍길동 회원님!"

이라는 결과를 보인다. 끝.

 

 

 

반응형