ajax表单post函数返回400错误

时间:2017-09-14 06:23:49

标签: jquery ajax spring

我目前正在使用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]

1 个答案:

答案 0 :(得分:1)

$.ajax({
  type: "POST",
  url : "/Test",
  async: false,
  dataType : "json",
  data : JSON.stringify({id:"value of Id input", name: "value of name input"}),
  contentType: "application/json",
  success : function(result){
    if(result == null){
        alert("Succ");
    }
    else{
        alert("not null");
    }
  },
  error : function(){
    console.log('here');
    alert($("#Form").serialize());
  }});

请求主体中的JSON对象必须与后端模型PersonRequest匹配