當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring MVC —— 前后台传递JSON
生活随笔
收集整理的這篇文章主要介紹了
Spring MVC —— 前后台传递JSON
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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(data.msg);},error:function(){} });Java代碼:
@RequestMapping(params= "testAJax") public voidtestAjax(@RequestParam String id,String name,HttpServletRequest req){Stringid2 = req.getParameter("id");Stringname2 = req.getParameter("name");System.out.println("1111"); }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(){} });Java:
@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> carnums4. 后臺返回前臺JSON,需要在返回方法上加上@ResponseBoby,代表將JSON數據放到Http Boby中返回
返回值標識了@ResponseBody,SpringMVC將使用StringHttpMessageConverter的write()方法,將結果作為String值寫入響應報文,當然,此時canWrite()方法返回true。
關于HttpMessageConverter和@RequestBody、@ResponseBody的關系請看我另一篇文章。
轉載于:https://www.cnblogs.com/yifanSJ/p/9226853.html
新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的Spring MVC —— 前后台传递JSON的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是Docker??
- 下一篇: gradle idea java ssm