1. 若是使用@RequestBody接受頁面參數: public Map<String,Object> insertBudget(@ApiParam(required = true,name = "actBudgetCost",value = "預算")@RequestBody ActBudgetCost actBudgetCost, HttpServletRequest request){ } 那麼前臺頁面ajax應該這樣寫: $.ajax({ url: '', type: "POST", data: JSON.stringify({ "actiName":name }), dataType: "json", contentType: "application/json", async: false, success: function (result) { }, error: function (xhr, ajaxOptions, thrownError) { //console.log(thrownError); //alert any HTTP error //alert("請求出錯!"); return false; } }); 2. 若是不使用@RequestBody接受頁面參數: public Map<String, Object> regProduct(HttpServletRequest request, @ApiParam(name = "customerProAuditPO", value = "產品註冊實體")CustomerProAuditVO customerProAuditVO ) { } 那麼前臺頁面ajax應該這樣寫: var data = { customerName:customerName, }; $.ajax({ url:'', type: "POST", data: data, //async: false, dataType:"json", success: function(result) { var json = result; }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError); return false; } }); 複製代碼
因爲項目是先後端分離,所以後臺使用的是spring boot,作成微服務,只暴露接口。接口設計風格爲restful的風格,在get請求下,後臺接收參數的註解爲RequestBody時會報錯;在post請求下,後臺接收參數的註解爲RequestParam時也會報錯。html
2、問題緣由ajax
因爲spring的RequestParam註解接收的參數是來自於requestHeader中,即請求頭,也就是在url中,格式爲xxx?username=123&password=456,而RequestBody註解接收的參數則是來自於requestBody中,即請求體中。spring
3、解決方法json
所以綜上所述,若是爲get請求時,後臺接收參數的註解應該爲RequestParam,若是爲post請求時,則後臺接收參數的註解就是爲RequestBody。附上兩個例子,截圖以下:後端
get請求restful
post請求app
另外,還有一種應用場景,接口規範爲resultful風格時,舉個例子:若是要獲取某個id下此條問題答案的查詢次數的話,則後臺就須要動態獲取參數,其註解爲@PathVariable,而且requestMapping中的value應爲value="/{id}/queryNum",截圖以下:前後端分離