【发布时间】:2017-09-14 06:23:49
【问题描述】:
我目前正在使用 Spring Boot,我想将对象从 ajax 发送到控制器进行验证。我知道您可以使用 ModelAttribute 正常提交表单,但我想使用 ajax 提交以进行验证。但是 ajax 函数每次都会返回 400 错误或 415 错误,我已经尝试到处寻找解决方案,但它并没有真正帮助。
我的看法:
<form id="Form">
<input name="id"></input>
<input name="name"></input>
<button type="submit" class="btn btn-default" id="button"></button>
</form>
<script>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url : "/Test",
async: false,
dataType : "json",
data : $("#Form").serialize(),
contentType: "application/json",
success : function(result){
if(result == null){
alert("Succ");
}
else{
alert("not null");
}
},
error : function(){
console.log('here');
alert($("#Form").serialize());
}
});
});
});
</script>
我的控制器:
@RequestMapping(value = "/Test",method = RequestMethod.POST)
public @ResponseBody PersonRequest test(@RequestBody PersonRequest person) {
return person;
}
我的实体:
public class PersonRequest {
@NotNull
private long id;
@NotEmpty
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PersonRequest() {
super();
}
}
如果我从 ajax 函数中删除 contentType: "application/json" 它会返回 415 错误,如果我保留它会返回 400 错误。请帮忙。
Browser console IDE 控制台返回以下错误:
.w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'id': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'id': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@1fc7f789; line: 1, column: 4]
【问题讨论】:
-
$("#Form").serialize() 给你一个字符串,你需要把你的html表单变成一个json对象,然后把它传递给spring控制器
-
哦...原谅我的无知,但我如何将其解析为 JSON。我对此有点陌生。提前致谢
-
请看下面我的回答,将 $("#Form").serialize() 替换为 {id:"value of Id input", name:"value of name input"}
-
即使我更换它,我仍然收到错误 400。没有别的办法吗?