【问题标题】:ajax form post function return a 400 errorajax 表单发布函数返回 400 错误
【发布时间】: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。没有别的办法吗?

标签: jquery ajax spring


【解决方案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 匹配

【讨论】:

  • 有什么方法可以发送整个表单,而不必像您说的那样将每个属性都放入数据{}?因为如果对象有更多的属性,那就很难做到了
  • @NganCun 我在发布前更新了字符串化 json 对象的答案。如果从 html 表单构造一个 json 对象的条款,已经有一个优雅的解决方案。 stackoverflow.com/questions/1184624/…
猜你喜欢
  • 1970-01-01
  • 2022-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
相关资源
最近更新 更多