【问题标题】:400 Bad request error in Ajax call to Spring controller400 对 Spring 控制器的 Ajax 调用中的错误请求错误
【发布时间】:2014-04-07 09:55:40
【问题描述】:

我正在尝试向 Spring 控制器发送数据,但在浏览器控制台中收到 400 badrequest 错误。 这是我的代码:

javascript:

function insertDiscussion(title, content,tags) {
    $.ajax({
        async:false,
        url: 'save',
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        dataType: 'json',
        data: {
            "title": title,
            "content": content,
            "tags":tags
        },
        success: function(data) {
            generateNoty(data, "warning");
        }
    });
}

控制器:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveDiscussion(
        @RequestParam String title,
        @RequestParam String content, @RequestParam(value="tags") String[] tags) {
    return "hello";
}

如果我们不发送数组,示例正在运行。当我尝试发送数组时,它给出 400 Bad Request 错误。

如果我通过链接访问同一个控制器,它可以正常工作,但不能使用 jquery ajax。我错过了什么吗?

【问题讨论】:

  • 仅供参考 async: false 已弃用,不应使用。
  • @RoryMcCrossan 我尝试了使用和不使用 async: false 。但它不起作用。
  • @igniter 这不是他的意思

标签: javascript jquery ajax spring spring-mvc


【解决方案1】:

您期望 @RequestParamPOST/GET 参数)但发送 JSON 作为请求正文。您需要改用@RequestBody

试试

public String saveDiscussion(@RequestBody Map json) {
    return "hello";
}

另见:

【讨论】:

  • 我正在使用 spring mvc 3.1.1 并且没有可用于 @RequestModel 注释的包。是否有新的注释。到目前为止,我在谷歌上没有找到任何关于此的内容。
  • 我的错,对不起。它的@RequestBody。还有一个——我从来没有尝试过@RequestBodyMap,通常它是一些类,其中包含从请求中映射的字段。但相信 Spring 也可以使用 Map
猜你喜欢
  • 2013-08-03
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 2019-06-19
  • 2015-06-12
  • 2015-02-11
  • 1970-01-01
相关资源
最近更新 更多