`

spring mvc 与 jquery ajax

 
阅读更多

在 Spring mvc3中,响应、接受 JSON都十分方便。 
使用注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON。 
使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON,Spring 会自动将其拼装成 bean。 

Spring这个转换是靠org.codehaus.jackson这个组件来实现的,所有需要引入jackson-core-asl和org.codehaus.jackson两个jar包 

 

[html] view plaincopy
 
  1. <title>Spring MVC</title>  
  2. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>  
  3. <script type="text/javascript" src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script>  
  4. <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/user/index.js"></script>  
  5. </head>  
  6. <body>  
  7. <div id="info"></div>  
  8. <form action="add" method="post" id="form">  
  9. 编号:<input type="text" name="id"/>  
  10. 姓名:<input type="text" name="username"/>  
  11. 年龄:<input type="text" name="age"/>  
  12.   
  13. <input type="button" value="提交" id="submit"/>  
  14. </form>  
  15. </body>  
  16. </html>  

 

[javascript] view plaincopy
 
  1. //将一个表单的数据返回成JSON对象  
  2. $.fn.serializeObject = function() {  
  3.   var o = {};  
  4.   var a = this.serializeArray();  
  5.   $.each(a, function() {  
  6.     if (o[this.name]) {  
  7.       if (!o[this.name].push) {  
  8.         o[this.name] = [ o[this.name] ];  
  9.       }  
  10.       o[this.name].push(this.value || '');  
  11.     } else {  
  12.       o[this.name] = this.value || '';  
  13.     }  
  14.   });  
  15.   return o;  
  16. };  
  17.   
  18. $(document).ready(  
  19.     function() {  
  20.       jQuery.ajax( {  
  21.         type : 'GET',  
  22.         contentType : 'application/json',  
  23.         url : 'user/list',  
  24.         dataType : 'json',  
  25.         success : function(data) {  
  26.           if (data && data.success == "true") {  
  27.             $('#info').html("共" + data.total + "条数据。<br/>");  
  28.             $.each(data.data, function(i, item) {  
  29.               $('#info').append(  
  30.                   "编号:" + item.id + ",姓名:" + item.username  
  31.                       + ",年龄:" + item.age);  
  32.             });  
  33.           }  
  34.         },  
  35.         error : function() {  
  36.           alert("error")  
  37.         }  
  38.       });  
  39.       $("#submit").click(function() {  
  40.         var jsonuserinfo = $.toJSON($('#form').serializeObject());  
  41.         alert(jsonuserinfo);  
  42.         jQuery.ajax( {  
  43.           type : 'POST',  
  44.           contentType : 'application/json',  
  45.           url : 'user/add',  
  46.           data : jsonuserinfo,  
  47.           dataType : 'json',  
  48.           success : function(data) {  
  49.             alert("新增成功!");  
  50.           },  
  51.           error : function(data) {  
  52.             alert("error")  
  53.           }  
  54.         });  
  55.       });  
  56.     });  

 

[java] view plaincopy
 
  1. @Controller  
  2. @RequestMapping("/user")  
  3. public class DemoController {  
  4.   private Logger logger = LoggerFactory.getLogger(DemoController.class);  
  5.   
  6.   @RequestMapping(value = "/list", method = RequestMethod.GET)  
  7.   @ResponseBody  
  8.   public Map<String, Object> getUserList() {  
  9.     logger.info("列表");  
  10.     List<UserModel> list = new ArrayList<UserModel>();  
  11.     UserModel um = new UserModel();  
  12.     um.setId("1");  
  13.     um.setUsername("sss");  
  14.     um.setAge(222);  
  15.     list.add(um);  
  16.     Map<String, Object> modelMap = new HashMap<String, Object>(3);  
  17.     modelMap.put("total""1");  
  18.     modelMap.put("data", list);  
  19.     modelMap.put("success""true");  
  20.     return modelMap;  
  21.   }  
  22.   
  23.   @RequestMapping(value = "/add", method = RequestMethod.POST)  
  24.   @ResponseBody  
  25.   public Map<String, String> addUser(@RequestBody UserModel model) {  
  26.     logger.info("新增");  
  27.     logger.info("捕获到前台传递过来的Model,名称为:" + model.getUsername());  
  28.     Map<String, String> map = new HashMap<String, String>(1);  
  29.     map.put("success""true");  
  30.     return map;  
  31.   }  
  32. }  


另外一种参数传递方式

 

前端代码:

 

[javascript] view plaincopy
 
  1. $.ajax({type : "POST",  
  2.        url : "assign.v",   
  3.        data : {  
  4.            userId : userId,  
  5.            'add[]' : [1,2,3],  
  6.            'del[]' :[4]  
  7.        },  
  8.        success : function (data){  
  9.            searchWidget.searchUser(1);    
  10.        }  
  11. });  

 


后端代码:

 

[java] view plaincopy
 
  1. @ResponseBody  
  2. @RequestMapping(value="/assign",  
  3.         method=RequestMethod.POST)   
  4. public String assign(  
  5.         @RequestParam(value="userId", required=trueint userId,  
  6.         @RequestParam(value="add[]", required=falseint[] add,  
  7.         @RequestParam(value="del[]", required=falseint[] del) {  
  8.     System.out.println("userId:" + userId);  
  9.     System.out.println("add:" + add);  
  10.     System.out.println("del:" + del);  
  11.     return "";  
  12. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics