本文目前仅记录发现的问题,具体原理部分等我学会后再行补充。
参数格式1
前端代码
let data = {
"orderId": id,
"userId": userId,
"sex": sex,
"phone": phone,
"approvedComments": approvedComments,
"customerId": customerId,
"info": "succ"
};
let dataJSON = JSON.stringify(data) // 将对象或值转成JSON字符串格式
$.ajax({
type: 'POST',
url: `${MODULE_PATH}reviewOrder`,
dataType: 'json',
contentType: 'application/json', // 说明请求参数格式是JSON字符串
data: dataJSON,
success: function (result) {
if (result.code == 200) {
layer.msg(result.msg, {time: 1500, icon: 6});
} else {
layer.msg(result.msg, {time: 1500, icon: 5});
}
}
})
后台接收代码
/*
方法一:用对象接收
*/
// 生成一个接收前端参数的对象
@Data // 这里如果不加setter/getter方法会报错
public class TestReception {
private Integer orderId;
private Integer userId;
private String sex;
private String phone;
private String approvedComments;
private Integer customerId;
private String info;
}
// 接口接收参数:注意要加入@RequestBody注解:不加就接收不到
@PostMapping("reviewOrder")
@PreAuthorize("hasPermission('shop/order/main','shop:order:main')")
public Result reviewOrder(@RequestBody TestReception testReception) {
HashMap<String, Object> res = new HashMap<>();
return success(200, "查詢成功", res);
}
/*
方法二:用Map接收
*/
@PostMapping("reviewOrder")
@PreAuthorize("hasPermission('shop/order/main','shop:order:main')")
public Result reviewOrder(@RequestBody Map<String, Object> para) {
HashMap<String, Object> res = new HashMap<>();
return success(200, "查詢成功", res);
}
参数格式2
前端代码
let data = {
"orderId": id,
"userId": userId,
"sex": sex,
"phone": phone,
"approvedComments": approvedComments,
"customerId": customerId,
"info": "succ"
};
$.ajax({
type: 'POST',
url: `${MODULE_PATH}reviewOrder`,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded', // 说明请求参数格式是表单形式,这里如果没有这个参数,则默认就是这个格式
data: data , // 以对象形式传递参数
success: function (result) {
if (result.code == 200) {
layer.msg(result.msg, {time: 1500, icon: 6});
} else {
layer.msg(result.msg, {time: 1500, icon: 5});
}
}
})
后台接收代码
/*
方法一:直接将要接收的参数写在接口函数中,将会自动封装
*/
@PostMapping("reviewOrder")
@PreAuthorize("hasPermission('shop/order/main','shop:order:main')")
public Result reviewOrder(Integer orderId, Integer customerId) {
HashMap<String, Object> res = new HashMap<>();
return success(200, "查詢成功", res);
}
/*
方法二:通过HttpServletRequest来解析参数
*/
@PostMapping("reviewOrder")
@PreAuthorize("hasPermission('shop/order/main','shop:order:main')")
public Result reviewOrder(HttpServletRequest req) {
Integer orderId = (Integer) req.getAttribute("orderId");
HashMap<String, Object> res = new HashMap<>();
return success(200, "查詢成功", res);
}