ajax不同的提交方式对应后端接收方式不同
当后端用@ResquestParam接收时
@RequestMapping(value = "adminLogin",method = RequestMethod.POST)
@ApiOperation(value = "用户登录",notes = "用户名密码不能为空")
public AdminUserResult adminLogin(@RequestParam String userName,@RequestParam String passWord, HttpServletRequest request, HttpServletResponse response){
String header = request.getHeader("User-Agent");//如果该值为""或者null则为浏览器登录,否则是手机端登录
return adminUserService.login(userName, passWord);
}
前端的data用js对象传递
$('#btnLogin1').click(function () {
var userName = $("#userName").val();
var passWord = $("#passWord").val();
var param = {'userName':userName,'passWord':passWord}
$.ajax({
url:"/AdminUserController/adminLogin",
type: 'POST',
dataType:'json',
// data: JSON.stringify({
// userName:userName,
// passWord:passWord
// }),
data: param,
// headers:{
// "Content-Type": "application/json"
// },
success:function (data) {
console.log("请求数据成功,数据是"+data)
console.log(data.status)
if(data.status==200) {//登录成功
location.href = "index.html"
}
}
})
})
当后端用@RequestBody接收数据时
@RequestMapping(value = "adminLogin1",method = RequestMethod.POST)
@ApiOperation(value = "用户登录",notes = "用户名密码不能为空")
public AdminUserResult adminLogin1(@RequestBody AdminUser adminUser, HttpServletRequest request, HttpServletResponse response){
String header = request.getHeader("User-Agent");//如果该值为""或者null则为浏览器登录,否则是手机端登录
String userName = adminUser.getUserName();
String passWord = adminUser.getPassWord();
return adminUserService.login(userName, passWord);
}
要将data转为json格式并添加
headers:{
“Content-Type”: “application/json”
}
$('#btnLogin2').click(function () {
var userName = $("#userName").val();
var passWord = $("#passWord").val();
var param = {'userName':userName,'passWord':passWord}
$.ajax({
url:"/AdminUserController/adminLogin1",
type: 'POST',
dataType:'json',
// data: JSON.stringify({
// userName:userName,
// passWord:passWord
// }),
data: JSON.stringify(param),
headers:{
"Content-Type": "application/json"
},
success:function (data) {
console.log("请求数据成功,数据是"+data)
console.log(data.status)
if(data.status==200) {//登录成功
location.href = "index.html"
}
}
})
})
使用swagger测试后端接口没问题,前端报400/415,按照上面的方法问题解决了。