JSON문자열을 서버측에서 Java로 수신하고 속성을 추가하여 다시 클라이언트에게 응답하는 예
json2.jsjson_simple-1.1.jar
client_ajax.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="./json2.js"></script>
<script type="text/javascript">
function createXMLHttpRequest(){
// See http://en.wikipedia.org/wiki/XMLHttpRequest
// Provide the XMLHttpRequest class for IE 5.x-6.x:
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
throw new Error( "This browser does not support XMLHttpRequest." )
};
return new XMLHttpRequest();
}
var AJAX = createXMLHttpRequest();
function req(){ /* JSON 문자열을 서버로 전송한다 */
var name = "김시준";
var jsonObj = {"name":name, "phone":"3456-745-567","age":15}; /* JSON객체생성 */
var jsonStr = jsonObj.toJSONString(); /* JSON문자열 생성*/
AJAX.open("POST", "json_service.jsp", true);
AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
AJAX.onreadystatechange = handler;
AJAX.send("info="+jsonStr); /* JSON문자열을 서버로 전송 */
}
function handler() {
if(AJAX.readyState == 4 && AJAX.status == 200) {
var json = eval('(' + AJAX.responseText +')'); /* 혹은 아래처럼.... */
/* var json = AJAX.responseText.parseJSON(); */
alert('응답내용. Result: name => ' + json.name + ',' + 'address => ' + json.address);
}else if (AJAX.readyState == 4 && AJAX.status != 200) {
alert('Something went wrong...');
}
}
</script>
<body>
<a href="#" onclick="javascript:req();"> Click here to send JSON data to the server side</a>
</html>
json_service.jsp
<%@page import="org.json.simple.*"%>
<%
request.setCharacterEncoding("utf-8");
JSONObject jsonObj = (JSONObject)JSONValue.parse(request.getParameter("info"));
String jsonStr = jsonObj.toJSONString();
/* 클라이언트가 전송한 JSON문자열을 서버콘솔에 출력해본다 */
System.out.println(jsonStr);
/* 클라이언트 측에서 전송한 JSON객체에 속성을 추가하여 다시 클라이언트에게 전송한다 */
jsonObj.put("address","서울시 종로구");
out.print(jsonObj);
out.flush();
%>