ajax, JSON 사용하기
1. SELECT로 하나의 데이터가 나올때 쓰는 경우
# JSP #
$.ajax({
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
type:"POST",
url:"/userLogin.do",
data: $("#form").serialize(),
dataType : 'json',
async: false,
success:function(data){
var resultCode = data.resultCode;
}
});
# JAVA #
@ResponseBody
@Transactional
@RequestMapping(value = "/userLogin.do")
public String loginUser(@ModelAttribute("vo") PlanResearcherVO vo, PlanResearcherVO failVo, ModelMap model, HttpServletRequest request, HttpSession sess) throws Exception {
JSONObject json = new JSONObject();
vo = planService.UserLogin(vo);
json.put("resultCode","0000"); //클라이언트 단에서 data.resultCode; 이런식으로 데이터를 꺼낼 수 있다
return json.toString();
}
2.JSON array 를 사용할 경우 (SELECT로 로우데이터를 가져올 경우 쓴다)
# JSP #
var addData = { "FM_SEQ": seq };
$.ajax({
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
type:"POST",
url:"/farmerCropInfo.do",
data: addData,
dataType : 'json',
success:function(data){
for(ver i=0; i<data.length; i++){
var crType = data[i].CR_TYPE;
}
}
});
# JAVA #
@ResponseBody
@Transactional
@RequestMapping(value = "/planMapSelect.do")
public String planMapSelect(@ModelAttribute("vo") PlanLandVO vo, ModelMap model, HttpServletRequest request, HttpSession sess) throws Exception {
List<PlanLandVO> list = planService.PlanAddrList(vo);
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
for(int i =0; i<list.size(); i++){
json.put("SEQ", list.get(i).getSEQ());
jsonArray.add(json); //클라이언트 단에서 data[i].SEQ; 이런식으로 데이터를 꺼낼 수 있다
}
return jsonArray.toString();
}