問(wèn)題
今天遇到一個(gè)問(wèn)題,代碼如下
java:
1
2
3
4
5
|
@postmapping (value = "/method" ) @responsebody public object method(integer id,string audit_content) { return null ; } |
js:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
var data = {id: 7 ,audit_content: "11111111111111111111a1" }; $.ajax({ type: "post" , url: "/method" , data:data, contenttype: "application/json;charset=utf-8" , success: function (result) { $( "#my_result" ).html(json.stringify(result)); }, error: function () { console.log( "shibai" ) } }); |
這樣的話,java后臺(tái)的id和audit_content永遠(yuǎn)都是null;就算用httpservletrequest的getparameter("id")也一樣沒(méi)用。
解決
原因是js代碼里的contenttype: "application/json;charset=utf-8",刪掉或者改成默認(rèn)的"contenttype: application/x-www-form-urlencoded"就行了。
拓展
那么什么時(shí)候用contenttype: "application/json;charset=utf-8"呢,后臺(tái)不是接收單個(gè)字符串,而是一個(gè)實(shí)體類(lèi)時(shí)就用它了。
java代碼:
1
2
3
4
5
6
|
@postmapping ( "/method2" ) @responsebody @transactional public object method2( @requestbody body body) { return null ; } |
js代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
var data = { "id" : i, "show_status" : 0 }; $.ajax({ type: "post" , url: "/method2" , data: json.stringify(data), contenttype: "application/json;charset=utf-8" , success: function (result) { $( "#my_result" ).html(json.stringify(result)); }, error: function () { console.log( "shibai" ) } }); |
這樣java后臺(tái)會(huì)得到一個(gè)有id和show_status屬性的body類(lèi),注意一定要json.stringify(data),不能直接傳data。
以上這篇解決springmvc接收不到ajaxpost參數(shù)的問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/mr_ooo/article/details/74675035