您的位置:首页 > 编程语言 > Java开发

Spring MVC前后台传递JSON

2017-03-19 21:10 155 查看
1. 传递JSON参数

                   vardata = {'id':1,'name':'abc'};

                   $.ajax({

                            type:'post',

                            url:'homePageAction.do?testAJax',

                   contentType:'application/x-www-form-urlencoded',

                            data:JSON.stringify(data),

                            success:function(data){

                                     console.log("aaaaaaaaaaa")

                                     console.log(data.msg);

                            },

                            error:function(){

                            }

                   });

//       @RequestMapping(params= "testAJax")
//       public voidtestAjax(@RequestParam String id,String name,HttpServletRequest req){
//                Stringid2 = req.getParameter("id");
//                Stringname2 = req.getParameter("name");
//                System.out.println("1111");
//                System.out.println("2222");
//       }

2. 传递JSON对象或JSON数组(后台接收使用EventInfo[],而不是List<EventInfo> list)

                   vardata = [{'id':1,'name':'abc'},{'id':2,'name':'def'},{'id':3,'name':'ghi'}];

                   console.log(JSON.stringify(data));

                   $.ajax({

                            type:'post',

                            url:'homePageAction.do?testAJax',

                            contentType:'application/json',

                            data:JSON.stringify(data),

                            success:function(data){

                                     console.log(data.msg);

                                     console.log(data.obj.id);

                                     console.log(data.obj.name);

                            },

                            error:function(){

                            }

                   });

//       @RequestMapping(params= "testAJax")
//       @ResponseBody
//       publicJSONObject testAjax(@RequestBody EventInfo[] ei,HttpServletRequest req){
//                Longid1 = ei[0].getId();
//                Stringname1 = ei[0].getName();
//                JSONObjectjo = new JSONObject();
//                jo.put("msg","return success");
//                jo.put("obj",ei[0]);
//                return jo;
//       }

3. 传递JSON数组,后台用List接收

                  前端Ajax传参数:

                  [ "0866282192144020" ]

                  后端Spring方法接收参数:

                  @RequestParam("carnums[]") List<String> carnums

4. 后台返回前台JSON,需要在返回方法上加上@ResponseBoby,代表将JSON数据放到Http Boby中返回

返回值标识了@ResponseBody,SpringMVC将使用StringHttpMessageConverter的write()方法,将结果作为String值写入响应报文,当然,此时canWrite()方法返回true。

关于HttpMessageConverter和@RequestBody、@ResponseBody的关系请看我另一篇文章。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: