Java 后端 Controller 使用 POST 方法接收前端对象参数详解
前端代码示例:
// 定义一个对象
var data = {
'name': '张三',
'age': 20,
'gender': '男'
};
// 使用jQuery的ajax方法发送post请求,并将对象作为参数传递给后端controller
$.ajax({
type: "POST",
url: "/api/user",
data: JSON.stringify(data),
contentType: "application/json",
dataType: "json",
success: function(response) {
// 请求成功后的处理逻辑
console.log(response);
},
error: function(xhr, status, error) {
// 请求失败后的处理逻辑
console.log(error);
}
});
说明:
-
首先定义一个对象,包含需要传递给后端 controller 的数据。
-
使用 jQuery 的 ajax 方法发送 post 请求,其中:
-
type: 请求类型为 POST;
-
url: 请求的地址为
/api/user,根据实际情况修改; -
data: 将对象转换为 JSON 字符串,并作为请求体发送给后端;
-
contentType: 请求体的类型为
application/json; -
dataType: 响应数据的类型为 JSON;
-
success: 请求成功后的回调函数,参数为响应数据;
-
error: 请求失败后的回调函数,参数为 XMLHttpRequest 对象、错误状态和错误信息。
-
-
最后在 success 和 error 回调函数中分别处理请求成功和请求失败的情况。
原文地址: https://www.cveoy.top/t/topic/ot3E 著作权归作者所有。请勿转载和采集!