搗鼓了快一天時間翻了很多別人的文章。
也發現了很多人寫東西根本不負責任。明明錯的自己沒去試過還是轉載了。導致我也浪費了很多時間。
所以我決定以后自己遇到問題自己記錄下來。
開始說下問題。前台用ajax發送post請求。后台怎么也接受不到。
java代碼:
function phoneValidate(phone){
var flag = false;
$.ajax({
type:"post",
contentType : "application/json; charset=utf-8",
data: JSON.stringify({'phone':phone}),
url:"phoneInUse.go",
dataType: "json",
async: false,
success:function(result){
result = eval(result);
if(result.valid){
flag = true;
}
else{
alert(result.message);
flag = false;
}
}
});
return flag;
}
后台代碼:
/** 手機號是否已經被注冊*/
@RequestMapping(value = "/phoneInUse", method=RequestMethod.POST, produces="application/json; charset=utf-8")
public String phoneInUse(@RequestParam(value = "phone", required = true) String phone){
try {
User user = userService.getUserByPhone(phone);
if (user != null && user.getId() != null) {
return "{\"valid\":false,\"message\":\"手機號已被占用!\"}";
}
} catch (Exception e) {
log.error("登錄名驗證失敗", e);
e.printStackTrace();
return "{\"valid\":false,\"message\":\"網站程序錯誤!\"}";
}
return "{\"valid\":true}";
}
問題出在:@RequestParam 不能接收 contentType : "application/json; charset=utf-8" 的請求。
如果后台必須要用@RequestParam,
前台2個地方必須改:
1、contentType 改為 "application/x-www-form-urlencoded"
2、data: 改為{'phone':phone},
也可以不用改前台的js后台的@RequestParam....改為用@RequestBody的對象的形式
