ajax 前后向后台传递json 数据
contentType 默认值 "application/x-www-form-urlencoded" 适合于大多数请求json text xml 等都会自动进行解析;
contentType为application/json 适用于 向后台传递json字符串 , 此时data 里面需要用 JSON.stringify()进行序列化,将其转为json形式的字符串。传递到后台!
如:
var data = {'receive':receive};
$.ajax({
url:"url",
type:"post",
data:JSON.stringify(data),
contentType:"application/json;charset=utf-8", //必须要设置
dataType: "json",//返回的数据格式为json
success:function (result) {
if (result.code==0){
alert("发送成功!");
}else {
alert("发送失败!");
}
},
error:function () {
alert("网络异常,请稍后再试!");
}
});
后台接收
@PostMapping(value = "sendEmail")
@ResponseBody //返回数据设置在body中
public ResultModel sendEmail(@RequestBody JSONObject obj ){
boolean flag = false;
...
return flag?new ResultModel(0,"ok"):new ResultModel(1,"no");
}
contentType为application/json 不写的话 ,传递值为json对象
var data = {'receive':receive};
$.ajax({
url:"url",
type:"post",
data:data,
dataType: "json",//返回的数据格式为json
success:function (result) {
if (result.code==0){
alert("发送成功!");
}else {
alert("发送失败!");
}
},
error:function () {
alert("网络异常,请稍后再试!");
}
});
后台接收
@PostMapping(value = "sendEmail")
@ResponseBody //返回数据设置在body中
public ResultModel sendEmail(String fileName, String receive , String yfphm){
boolean flag = false;
...
return flag?new ResultModel(0,"ok"):new ResultModel(1,"no");
}
或者
利用pojo,用@RequestBody接收
@PostMapping(value = "sendEmail")
@ResponseBody //返回数据设置在body中
public ResultModel sendEmail(@RequestBody Pojo pojo){
boolean flag = false;
...
return flag?new ResultModel(0,"ok"):new ResultModel(1,"no");
}
网友评论