Ajax 데이터 전송 예제 Jquery Json 전자정부 표준프레임워크 컨트롤러
전자정부 프레임워크에서 ajax를 이용 json 객체를 전송하는 예제입니다
1. 자바스크립트에서 json 객체를 ajax 전송
2. 컨트롤러에서 json을 받아 로직 처리 후 json 리턴
3. 자바스크립트에서 json 받아서 html에 출력
JavaScript : JavaScript를 사용하여 json객체를 전송
1. ajax.jsp 생성
2. jquery 임포트 <script src="js/jquery-2.1.4.js"></script>
3. user객체에 key, value쌍 등록 user.key = value;
4. user를 json형태로 스트링화 var jsonString = JSON.stringify(user);
5. ajax로 url,type,data,success,error 작성
- url은 ajax명령을 처리할 컨트롤러 맵핑
- type은 post
- data에는 jsonString을 request에 담기위해 "name" : value형태로 저장
- success에는 결과값을 처리할 내용 작성 result는 컨트롤러가 return하는 값 (String 리턴필요)
- error에는 에러시 내용 작성
<script> var user = new Object(); //컨트롤러로 전송할 객체 user.name = "이름"; user.age = "27"; var obj = new Object(); //컨트롤러의 리턴값(result)을 저장할 객체 $('#ajaxButton').click(function(){ var jsonString = JSON.stringify(user); console.log(jsonString); $.ajax({ url:'./ajaxProcess.do', //request 보낼 서버의 경로 type:'post', // 메소드(get, post, put 등) data: {"jsonString":jsonString}, //보낼 데이터 success: function(result) { //서버로부터 정상적으로 응답이 왔을 때 실행 alert("success! \n"+result); //result를 obj객체로 파싱하여 사용 obj = jQuery.parseJSON(result); console.log(obj.name); console.log(obj.age); console.log(obj.gender); }, error: function(err) { //서버로부터 응답이 정상적으로 처리되지 못햇을 때 실행 alert("error! : "+err); } }); }); </script>
Java : Controller에서 json 객체를 전달받아 로직처리 후 ajax로 리턴
1. @RequestMapping에 url 맵핑, 한글 인코딩 문제 해결을 위해
produces="text/html; charset=utf-8" 추가
2. jsonResult를 리턴하기위해 @ResponseBody 추가
3. jsonString을 받아오기 위해 인자에 HttpServletRequest request추가
4. request 사용해서 jsonString에 저장
5. jsonString.replaceAll(); 사용하여 쌍따옴표 복구
6. JSONParser, JSONObject 사용하여 jsonString을 json객체로 변환
(google JSON-simple 클래스 사용 maven)
7. json.put(), json.get()메서드 사용하여 데이터 로직 처리
8. json.toString()사용하여 json객체를 jsonResult 스트링으로 변환
9. jsonResult를 ajax로 리턴
@RequestMapping(value = "/ajaxProcess.do", produces="text/html; charset=utf-8") //인코딩 문제 해결 @ResponseBody //리턴하기 위해 추가 public String ajaxProcess(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { //request를 사용하여 jsonString 쌍따옴표 복구 후 저장 String jsonString = request.getParameter("jsonString"); jsonString = jsonString.replaceAll("&quot;", "\""); //쌍따옴표 복구 System.out.println("Controller > jsonString : "+jsonString); //자바콘솔에 스트링 출력 //jsonParser 사용해서 json 객체로 파싱 JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(jsonString); //json객체를 사용해서 필요한 로직 처리 json.put("gender", "남자"); //json객체를 jsonResult 스트링으로 변경 후 ajax의 result로 리턴 String jsonResult = json.toString(); return jsonResult; }
JavaScript : Javascript에서 Json 객체를 전송받아 html에 표현
1. result를 obj 객체로 변환 obj = jQuery.parseJSON(result);
2. obj 사용 하여 콘솔에 출력 console.log(obj.name);
var obj = new Object(); ... $.ajax({ ... success: function(result) { //서버로부터 정상적으로 응답이 왔을 때 실행 alert("success! : "+result); //result를 obj객체로 파싱하여 사용 obj = jQuery.parseJSON(result); console.log(obj.name); console.log(obj.age); console.log(obj.gender); },