1. 程式人生 > >Spring MVC —— 前後臺傳遞JSON

Spring MVC —— 前後臺傳遞JSON

後臺 print col 方法 http .ajax AS RR map

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> carnums

4. 後臺返回前臺JSON,需要在返回方法上加上@ResponseBoby,代表將JSON數據放到Http Boby中返回

返回值標識了@ResponseBody,SpringMVC將使用StringHttpMessageConverter的write()方法,將結果作為String值寫入響應報文,當然,此時canWrite()方法返回true。

關於HttpMessageConverter和@RequestBody、@ResponseBody的關系請看我另一篇文章。

Spring MVC —— 前後臺傳遞JSON