1. cross broser
브라우저 종류에 상관없이 동작하도록 구현
2. helloAPP.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">
<head>
<meta http-equiv="content-type" content="text/html; charset=euc-kr" />
<title>안녕하세요!</title>
<script type="text/javascript" src="httpRequest.js"></script>
<script type="text/javascript">
function helloToServer() {
// 서버로 전송하는 한글값은 utf-8로 변환해서 보내자
var params = "name="+encodeURIComponent(document.f.name.value);
sendRequest("hello.jsp", params, helloFromServer, "POST");
// XMLHttpRequest는 보안상 같은 도메인의 url만 처리
// method는 POST 또는 GET
}
function helloFromServer() {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert("서버응답:"+httpRequest.responseText);
}
}
// 처리중인 작업 표시는 httpRequest.readyState == 1 로 체크함이 cross browser 지원을 위해 좋을듯
// readyState : 0 uninitalized, 1 loading, 2 loaded, 3 interative, 4 completed
// status : 200 ok, 403 forbidden, 404 not found, 500 internal server error
}
</script>
</head>
<body>
<form name="f">
<input type="text" name="name" />
<input type="button" value="입력" onclick="helloToServer()" />
</form>
</body>
</html>
3. httpRequest.js
function getXMLHttpRequest() {
// ie
if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(e1) { return null; }
}
// etc
} else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return null;
}
}
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;
}
// 3번째 파라메터는 동기여부이다. true이면 httpRequest.send 이후의 함수도 곧바로 실행한다. cross browser 지원을 위해 true만 사용하자
httpRequest.open(httpMethod, httpUrl, true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.onreadystatechange = callback;
httpRequest.send(httpMethod == 'POST' ? httpParams : null);
}
4. hello.jsp
// jsp처럼 charset을 지정할 수 있으면 상관없지만, text 파일의 경우 charset을 지정할 수 없으므로 utf-8로 저장되지 않았다면 한글이 깨질 수 있다.
<%@ page contentType="text/plain; charset=euc-kr" %>
<%
// XMLHttpRequest 는 기본적으로 utf-8 이다.
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
System.out.println("name : " + name);
%>
안녕하세요, <%= name %> 회원님!




