springmvc ajax json Spring MVC 中 AJAX请求并返回JSON的示例
洛易 人气:0想了解Spring MVC 中 AJAX请求并返回JSON的示例的相关内容吗,洛易在本文为您仔细讲解springmvc ajax json的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:springmvc,ajax,json,spring,mvc,ajax请求,spring,ajax,json,下面大家一起来学习吧。
一、以ModelAndView的方式返回
先看下JavaScript代码:
/** * 保存-同步(版本控制库) */ function saveSynchronizedVcHorse(obj) { var ss = $("#SynchronizedSelection div"); var cacheSelectAry = new Array() for(var i = 0; i < ss.length; i ++) { //alert(ss.eq(i).html()); //alert(ss.eq(i).find('label').html()); var o=ss.eq(i).find('label').find("input[type='checkbox']"); var s = $(o).attr('checked');//由于$(obj).attr("checked", false); checked属性会被 if(s != null) { cacheSelectAry.push($(o).attr('value')); } } if(cacheSelectAry.length == 0) { alert("请选择城市"); return; } var json = "SynchronizedBean={\"exceptionId\":\""+exceptionId+"\",\"cityIds\":[" for(var i = 0; i < cacheSelectAry.length; i ++) { if(i == cacheSelectAry.length -1) { json = json +"\""+ cacheSelectAry[i] + "\""; } else { json = json + "\"" + cacheSelectAry[i] + "\","; } } json = json + "]}"; $.ajax({ type: "POST", dataType: "json", url: "../main/saveSynchronizedData", data: json, success: function(msg){ alert(msg.main); }, error: function () {//XMLHttpRequest, textStatus, errorThrown alert("请求失败"); } }); }
主要是看ajax请求部分。
再看Spring 中控制器的代码:
@RequestMapping(value = "/saveSynchronizedData", method = RequestMethod.POST) public @ResponseBody ModelAndView saveSynchronizedData(@RequestParam("SynchronizedBean") String mSynchronizedJSON) { ObjectMapper objectMapper = new ObjectMapper(); Map<String, String> map = new HashMap<String, String>(); try { SynchronizedBean bean = objectMapper.readValue(mSynchronizedJSON, SynchronizedBean.class); if(bean != null) { String[] ary = bean.getCityIds(); if(ary != null && ary.length > 0) { for(String s : ary) { VCHousePo po = new VCHousePo(); po.setExceptionId(bean.getExceptionId()); po.setCustomerCode(s); po.setCreateTime(new Date()); po.setExceptionState(0); vcHService.add(po); } } } map.put("msg", "success"); } catch (JsonParseException e) { e.printStackTrace(); map.put("msg", "error"); } catch (JsonMappingException e) { e.printStackTrace(); map.put("msg", "error"); } catch (IOException e) { e.printStackTrace(); map.put("msg", "error"); } return new ModelAndView(new MappingJackson2JsonView(),map); }
这里是通过ModelAndView的方式进行返回JSON的。另外:MappingJackson2JsonView使用的package是
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
加载全部内容