总结
@RequestParam()接收前端数据的情况:
POST请求“application/x-www-form-urlencoded’”,此时传参能用JSON.stringify(),,POST请求用“application/json”是后端要用@ResquestBody注解封装实体对象接收,不能用@RequestParam()。
GET请求时用“‘application/x-www-form-urlencoded’”或“application/json”都行,不用JSON.stringify()修饰传参数据
$.ajax({
type: 'get',
url: "Http://localhost:8080/user-attr/trace",
data: { "pid": data.uid },
contentType: 'application/json',
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (res) {
if (res.code == 200) {
//获取表单数据,并序列化
layero.find("#traceUsername").attr('value', res.data.username);
layero.find("#traceAttr").attr('value', res.data.attributes);
} else {
layer.alert(res.msg, { icon: 5 }, function (index) {
layer.close(index);
});
}
}
});
@RequestBody接收前端数据
前端用form数据或者用自定义json数据传参(无法用form表单数据的情况下,不要用FormData构造,并用JSON.stringify()修饰)
$.ajax({
type: 'post',
url: "Http://localhost:8080/user-attr/updateUser",
data: JSON.stringify({"id":data.id,"info":data.Id,"username":formObject[0].value,"type":formObject[1].value,"attributes":arr_box.toString()}),
contentType : 'application/json',
dataType : 'json',
xhrFields: {
withCredentials: true
},
success: function (res) {
if (res.code==200) {
layer.alert(res.data, {icon: 1}, function (index) {
layer.close(index);
// window.location.reload();
});
} else {
layer.alert(res.msg, {icon: 5}, function (index) {
layer.close(index);
});
}
}
});
前端传自定义json参数 post请求
这是后端用@RequestParam的情况,自定义json参数 post请求时,不能用JSON.stringify()函数转化Form或FormData作为传参数据
$.ajax({
url: "Http://localhost:8080/file/search",
type : "POST",
contentType : 'application/x-www-form-urlencoded',
dataType : 'json',
data: {"keywords" : data.field.keywords, "userId" : sessionStorage.getItem('userId')},
success: function (res) {
if (res.code==200) {
resu = res.data;
} else {
layer.alert(res.msg, {icon: 5}, function (index) {
layer.close(index);
});
}
}
});
Form表单Post 请求
$.ajax({
type: 'post',
url: "Http://localhost:8080/user/register",
data: JSON.stringify(data),
contentType : 'application/json',
dataType : 'json',
success: function (res) {
if (res.code==200) {
layer.msg('注册成功', function () {
window.location = 'login-3.html';
});
} else {
layer.alert(res.msg, {icon: 5}, function (index) {
layer.close(index);
});
}
}
});