【问题标题】:Jquery Ajax POST not working. works fine for GETJquery Ajax POST 不工作。适用于 GET
【发布时间】:2015-06-03 17:06:58
【问题描述】:

我正在尝试发布 jquery Ajax 请求,但它没有发送到我的 MVC 控制器。

$.ajax({
            url : contextPath + "/check/panelnumber",
            type : "POST",
            contentType : "application/json",               
            data :{
                    "execution" : execution,
                    "panelNumber" : panelNumber
            },
});

Spring MVC 控制器

@Controller
@RequestMapping("/check")
public class ValidateFieldValueController extends FlowEnabledBaseController {

@RequestMapping(value = "/panelnumber", method = RequestMethod.POST)
public ResponseEntity<String> checkPanelNumber(HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam("panelNumber") String panelNumber,
        @RequestParam("execution") String execution) {
......
Gson gson = new Gson();
return new ResponseEntity<String>(gson.toJson(details), HttpStatus.OK);
}

但是它对于 GET 方法非常有效! 尝试添加 dataType: "json" ,但即使 GET 调用也停止工作。浏览器控制台显示错误为 HTTP 400 错误请求,但通过 firefox 插件检查时,POST 参数正常。 有什么帮助吗?

【问题讨论】:

  • $.ajax 调用的匹配右括号在哪里?
  • 这是错字...已更正问题
  • 您似乎并没有真正发送 JSON,因此将 contentType 设置为 appliation/json 没有意义。

标签: javascript jquery ajax spring-mvc


【解决方案1】:

当涉及到@RequestParam、POST 正文和 JSON 内容类型时,Spring 有点棘手:它根本不会解析它们。您可以通过以下三种方式之一解决此问题:

  1. 将内容类型更改为application/x-www-form-urlencoded
  2. 将两个@RequestParam 更改为一个@RequestBody Map&lt;String, Object&gt; body,然后使用该Map 手动解析出您的参数。
  3. 设置自定义Argument Resolver,它可以解析 JSON 以获得所需的值。

第二种方法可能是最容易更改的,但它会丢失一些 Spring 为您执行的自动验证。

【讨论】:

  • 它与选项 1 完美配合!非常感谢!
  • 选项 2 给了我 HTTP/1.1 415 Unsupported Media Type ?
  • 请参阅this answer 以了解选项 2 的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 2010-12-23
相关资源
最近更新 更多