一、以ModelAndView的方式返回
先看下JavaScript代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
/** * 保存-同步(版本控制库) */ 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 中控制器的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
@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;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/royi123/p/5239431.html