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",截图以下:前后端分离