Archive for the ‘ Ajax ’ Category

hello Ajax!

hello.html 에서 text form으로 이름을 받고, 이를 jsp 페이지에서 처리 후 alert을 띄워주는

우선 Javascript 코드를 따로 script/httpRequest.js 로 분리시켜놓고

<script type=”text/javascript” src=”script/httpRequest.js”></script>

를 head 부분에 작성하여 사용합니다.

hello.html 의 form 안에서 이름을 입력받아서 helloToServer() 함수를 호출하고 이름을 가져와서

ajax 처리를 위한 sendRequest()함수를 호출합니다.

처리된 결과는 다시 callback 함수인 helloFromServer() 함수에서 처리해서 결과코드를 분석하고 alert() 을 띄워주게 됩니다.

hello.html


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script type="text/javascript" src="script/httpRequest.js"></script>
<script type="text/javascript">
	function helloToServer(){
		var params = "name=" + encodeURIComponent(document.f.name.value);
		sendRequest("hello.jsp", params, helloFromServer, "POST");
	}

	// 서버로부터 응답
	function helloFromServer(){
		if(httpRequest.readyState == 4){
			if(httpRequest.status == 200){
				alert("서버응답:" + httpRequest.responseText);
			}
		}
	}
</script>
</head>
<body>
<form name="f">
	<input type="text" name="name" />
	<input type="button" value="입력" onclick="helloToServer()" />
</form>
</body>
</html>

hello.html 로부터 넘어오는 name 파라미터를 받아서 출력해주는 간단한 jsp 파일. (웹 서버 역할)

hello.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	request.setCharacterEncoding("utf-8");
	String name = request.getParameter("name");
%>
안녕하세요, <%= name %> 회원님!

httpRequest.js

ajax 의 단계로는 크게 4가지 단계가 있습니다.

  1. XMLHttpRequest 객체 생성
  2. open
  3. callback
  4. send

웹서버와 데이터를 주고 받기 위해서 XMLHttpRequest 객체를 생성하여 이를 이용해서 통신을 하고

open 함수를 이용해서 요청을 초기화,

onreadystatechange 프로퍼티로 웹 서버로 부터 응답을 처리할 callback 메서드를 지정합니다.

마지막 send 함수를 이용해서 요청을 웹서버로 전달합니다.

/*
 * XMLHttpRequest 객체를 생성해주는 함수
 */
function getXMLHttpRequest(){
	// IE
	if(window.ActiveXObject){
		try {
			return new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				return new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e1) {
				return null;
			}
		}
	// 비 IE
	} else if(window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else {
		return null;
	}
}

// XMLHttpRequest 객체를 저장하는 변수
var httpRequest = null;

// 요청 전송하는 함수
function sendRequest(url, params, callback, method){
	httpRequest = getXMLHttpRequest();
	var httpMethod = method ? method : 'GET';
	if(httpMethod != 'GET' && httpMethod != 'POST'){
		httpMethod = 'GET';
	}
	var httpParams = (params == null || params == '') ? null : params;
	var httpUrl = url;
	if(httpMethod == 'GET' && httpParams != null){
		httpUrl = httpUrl + "?" + httpParams;
	}
	// 요청 초기화, GET/POST 선택, 접속할 URL 입력
	httpRequest.open(httpMethod, httpUrl, true);
	// 전송할 컨텐트 타입 지정
	httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	// callback 지정
	httpRequest.onreadystatechange = callback;
	// 웹 서버에 요청 전송
	httpRequest.send(httpMethod == 'POST' ? httpParams : null);
}

Ajax 란 무엇인가?

Ajax는 비동기 자바스크립트와 XML(Asynchronous Javascript and XML을 의미한다.

엄밀히 말하면 Ajax 자체는 기술이라고 할 수 없다. 대신 잘 알려진 프로그래밍 기술들을 조합해서 웹 어플리케이션 인터페이스를 개발하도록 해주는 방법론이다.

관련 URL

wikipedia – http://ko.wikipedia.org/wiki/Ajax