Where The Streets Have No Name

JSON 예제 - 서버로 전송 본문

Developement/RIA

JSON 예제 - 서버로 전송

highheat 2006. 8. 13. 10:26

1) AJAX를 통해서 서버에 데이타를 보내는 경우

function getXmlHttpRequest() {
 if(window.XMLHttpRequest)
  return new XMLHttpRequest();
 else
  return new ActiveXObject("Microsoft.XMLHTTP");
}

function reqData() {
 var info = {};
 info['name'] = 'fantazic';
 info['url'] = 'http://fantazic.com';
 var encoded;
 try {
  encoded = JSON.stringify(info);
  //객체를 저장하는 경우
  //{"name":"fantazic","url":"http://fantazic.com"}
 } catch(e) {
  alert(e);
  return;
 }
 var xmlhttp = getXmlHttpRequest();
 xmlhttp.open("POST", "ajax_json.jsp", true);
 xmlhttp.setRequestHeader('Content-Type', \
 'application/x-www-form-urlencoded');
 xmlhttp.onreadystatechange = function() {
  if(xmlhttp.readyState == 4) {
   if(xmlhttp.status == 200) {
    try {
     var parsedObject = JSON.parse(xmlhttp.responseText);
     if(parsedObject.result == true) {
      alert('success');
     } else {
      alert(parsedObject.reason);
     }
    } catch(e) {
     alert(e);
     return;
    }
   }
  }
 }
 xmlhttp.send('info=' + encoded);
}

2) 서버쪽에서 데이타 처리 및 응답부분 (JAVA)

try {
 String info = request.getParameter("info");
 JSONObject getObj = new JSONObject(info);
 JSONObject returnObj = new JSONObject();
 if(getObj.get("name").equals("fantazic") \
 && getObj.get("url").equals("http://fantazic.com")) {
  returnObj.put("result", true);
 } else {
  returnObj.put("result", false);
  returnObj.put("reason", "입력내용이 잘못됐습니다.");
 }
 response.getWriter().print(returnObj.toString());
} catch(Exception e) {
 e.printStackTrace();
}