본문 바로가기

JSON/JSON 07, JSON Array Handling

JSON Array Sending, Receiving between Javascript and JSON-Simple

JSON 배열을 클라이언트와 서버가 주고 받는 예 (서버측에서는 JSON-Simple 사용)

json_simple-1.1.jar

json2.js
ajax_client.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(){

 var jsonArray = [{"name":"이수복", "phone":"356-745-567","age":25},
                  {"name":"권종식", "phone":"346-7845-679","age":35},
     ];
 jsonArray[2] = {"name":"서상석", "phone":"743-5687-9876","age":37};
 var jsonStr = jsonArray.toJSONString();
 alert(jsonStr);
 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);
}
 
function handler() {
  if(AJAX.readyState == 4 && AJAX.status == 200) {
      var jsonArray2 = eval('(' + AJAX.responseText +')');
      alert('응답내용. Result: name => ' + jsonArray2[3].name + ',' + 'phone => ' + jsonArray2[3].phone);
  }else if (AJAX.readyState == 4 && AJAX.status != 200) {
    alert('Something went wrong...');
  }
}

</script>
 
<body>
  <a href="#" onclick="javascript:req();"> Click here to send JSON Array string to the server side</a>
</html>


json_service.jsp

 <%@page contentType="text/html; charset=UTF-8"%>  
 <%@page import="org.json.simple.*"%>  
 <%
  request.setCharacterEncoding("utf-8");
  /* 클라이언트가 전송한 JSON배열의 문자열 표현을 서버측에서 JSON-Simple으로 수신하는 예 */
  JSONArray jsonArr = (JSONArray)JSONValue.parse(request.getParameter("info"));
  String jsonStr = jsonArr .toJSONString();
  
  /* 클라이언트가 전송한 JSON문자열을 서버콘솔에 출력해본다 */
  System.out.println(jsonStr);
  
  /* 클라이언트 측에서 전송한 JSON배열에 JSON객체를 추가하여  다시 클라이언트에게 전송한다 */
  JSONObject jobj = new JSONObject();
  jobj.put("name", "김창운");
  jobj.put("phone", "345-5687-789");
  jobj.put("age", 48);
  
 jsonArr.add(jobj);
  
 out.print( jsonArr );    
 out.flush();  
 %>