我正在尝试发布 jquery Ajax 请求,但它不会发送到我的 MVC Controller 。
$.ajax({
url : contextPath + "/check/panelnumber",
type : "POST",
contentType : "application/json",
data :{
"execution" : execution,
"panelNumber" : panelNumber
},
});
Spring MVC Controller
@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 参数正常。 有什么帮助吗?
最佳答案
Spring 在涉及 @RequestParam、POST 正文和 JSON 内容类型时有点敏感:它根本不会解析它们。您可以通过以下三种方法之一解决此问题:
- 将内容类型更改为
application/x-www-form-urlencoded
- 更改两个
@RequestParam
单例@RequestBody Map<String, Object> body
,然后使用Map
手动解析您的参数。 - 设置自定义 Argument Resolver可以解析 JSON 以获得您想要的值。
第二种方法可能是最容易更改的,但它会失去 Spring 为您提供的一些自动验证功能。
关于javascript - Jquery Ajax POST 不工作。对于 GET 来说效果很好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29350355/