web developer

[ajax] controller에서 ajax로 parameter 값을 String, VO, Map으로 넘기는 경우 본문

JavaScript

[ajax] controller에서 ajax로 parameter 값을 String, VO, Map으로 넘기는 경우

trueman 2022. 4. 14. 11:27
728x90
728x90

controller에서 ajax로 parameter 값을 String, VO, Map으로 넘기는 경우


1. controller

@RequestMapping(value = "/test.do", method = { RequestMethod.POST })
@ResponseBody /* 자바 객체를 HTTP 응답 본문의 객체로 변환 */

 /* Object 이외에도 String, list<pVO>, Map<String,Object> 등으로 대체 가능 */
public Object test(){
	
        // String
        String name = "뜨루";
        
        // Map
     	Map<String, String> map = new HashMap<String,String>(); 
        
        map.put("name","뜨루");
        map.put("age","28");
        map.put("gender","여자")
        
        // List
        List<pVO> list = service.testList(map);
        /* 
           list 값
           {"name":"뜨루"},
           {"age":"28"},
           {"gender":"여자."} 
        */
        
	return list;
	/* Ajax로 넘겨줄 parameter 값 (String, VO, Map) */
    	
}

2. ajax

$.ajax({
	url:  "test.do",
	type: "post",
    
	/* controllor에서 list를 return 받았음 */
	success : function(data) {
                        alert(data);
                        alert(data.name); 
                        alert(data.age);
                        alert(data.gender);
                        
	    	  /* 값이 여러개 일 때는 반복문 사용 : each문 */
           	  $.each(data,function(index, value) { 
                	alert(index); //index가 끝날 떄 까지
                	alert(value.name); 
                	alert(value.age); 
                	alert(value.gender);
            }
     },
	error : function() {
		alert("error");
	}
});

출처 : https://jackpang.tistory.com/48

728x90
728x90
Comments