Spring MVC 中 AJAX懇求並前往JSON的示例。本站提示廣大學習愛好者:(Spring MVC 中 AJAX懇求並前往JSON的示例)文章只能為提供參考,不一定能成為您想要的結果。以下是Spring MVC 中 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;
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。