我需要将字符串(或字符串数组)作为 JSON 对象发送到服务器,但我不断收到此消息 405 Method not allowed
或Bad request
如果我添加 csrf
参数+ token 。
这就是我正在尝试做的事情:
var data = { 'info': $('#theData').html() }; // data is: <p> bla <strong>bla</strong> bla </p>
$.ajax({
type: 'POST',
contentType : 'application/json',
dataType : 'json',
url: "editInfo", // ?${_csrf.parameterName}=${_csrf.token}", // `Bad Request`
data: JSON.stringify(data),
success: function(data){
$('#responseMsg').html('YES!').show(200);
},
error: function(el) {
var msg = 'Error ' + el.status + ': ' + el.statusText;
$('#responseMsg').html(msg).show(200);
}
});
这是 Controller :
@RequestMapping(value="editInfo", method = RequestMethod.POST, headers ="content-type=application/json")
public @ResponseBody String editInfo(
@RequestBody Info info,
HttpServletRequest request) {
// do stuff
return "success";
}
类(class)Info
只有 1 个名为 info
的字符串及其 getter 和 setter。理想情况下,我只想捕获 String 或 String 数组,但是无论什么都可以在没有得到的情况下工作 405 Method not allowed
最佳答案
嗯,一切看起来都很好,我无法重现它 - 添加 CSRF token 后您的网址会是什么样子?如果您设置静态参数(例如 url: "editInfo?param1=csrf_token"),您会得到 405 吗?
毕竟,问题可能是由于 Controller 方法定义不明确而发生的,所以这并不是真正的 jQuery 问题。
关于jquery - Spring MVC,Ajax post JSON对象,不允许405方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32672162/