當(dāng)controller方法的返回值為簡(jiǎn)單類型比如String時(shí),該如何與json交互呢?
使用@RequestBody
比如代碼如下:
1
2
3
4
5
|
@RequestMapping (value= "/ceshijson" ,produces= "application/json;charset=UTF-8" ) @ResponseBody public String ceshijson( @RequestBody String channelId) throws IOException{ return channelId; |
如果代碼為上面這種情況時(shí),前臺(tái)發(fā)送json時(shí),應(yīng)該這樣寫(xiě)(寫(xiě)法有很多,能用就行)
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
|
function channel(){ //先獲取選中的值 var channelId = $( "#channelId option:selected" ).val(); //來(lái)判斷發(fā)送的鏈接 if (channelId ==2){ $.ajax({ url: "ceshijson" , type: "post" , dataType: 'json' , contentType: 'application/json;charset=utf-8' , data:JSON.stringify({ 'channelId' :channelId}), success: function (data){ alert(data.channelId); }, error: function (XMLHttpRequest, textStatus, errorThrown){ alert( "Error" ) alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); } }); } } |
這里需要特別注意:上篇也強(qiáng)調(diào)過(guò),使用了@RequestBody時(shí),它要求String channelId接收到數(shù)據(jù)為json字符串。也就是要是data寫(xiě)成這樣: data:{‘channelId':channelId},就是錯(cuò)誤的。因?yàn)檫@是json對(duì)象形式。
要是你不想使用JSON.stringify()這個(gè)函數(shù),那就自己手動(dòng)字符串拼接:
1
|
data: '{"channelId":' +channelId+ '}' |
這里還要注意channelId是雙引號(hào),不能寫(xiě)成單引號(hào),因?yàn)檫@是json語(yǔ)法規(guī)則。你改成單引號(hào),也就是
**錯(cuò)誤寫(xiě)法
1
|
data: "{'channelId':" +channelId+ "}" |
這種形式,雖然可以傳給后臺(tái),但是后臺(tái)傳回來(lái)的會(huì)出現(xiàn)undefined。也就是key必須要用雙引號(hào)包圍。
不使用@RequestBody
1
2
3
4
5
6
7
8
9
|
@RequestMapping (value= "/ceshijson" ,produces= "application/json;charset=UTF-8" ) @ResponseBody public String ceshijson(String channelId) throws IOException{ Map<String,Object> map = new HashMap<String,Object>(); map.put( "channelId" , channelId); ObjectMapper mapper = new ObjectMapper(); channelId = mapper.writeValueAsString(map); return channelId; } |
前臺(tái)代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
$.ajax({ url: "ceshijson" , type: "post" , dataType: 'json' , //contentType:'application/json;charset=utf-8', data: "channelId=" +channelId, success: function (data){ alert(data); }, error: function (XMLHttpRequest, textStatus, errorThrown){ alert( "Error" ) alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); } }); |
這種方式利用ObjectMapper中的writeValueAsString將Java對(duì)象轉(zhuǎn)換為json字符串。
總結(jié):這種方式,其實(shí)是沒(méi)有多大的實(shí)際意思,因?yàn)橐话憬邮諗?shù)據(jù)不是這么接收的。只做了解!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/u013066244/article/details/50600092