jQuery AJAX 请求的“400 Bad Request”响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19546866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"400 Bad Request" response for AJAX request
提问by rob
I have the following jQuery AJAX request:
我有以下 jQuery AJAX 请求:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
来自服务器的响应是:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
" "status":400,"statusText":"Bad Request"
"客户端发送的请求在语法上不正确。
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
服务器正在运行 Spring-MVC。但据我所知,它工作正常。因为如果我使用 Postman 和以下配置手动发送请求,它就可以工作。
Header:
标题:
Content-Type application/json; charset=utf-8
Content:
内容:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
不得不提的是,这是一个跨域请求(开发的时候,以后会和服务器托管在同一个域上)。我确实禁用了浏览器中的安全设置,并且对服务器的 AJAX 请求工作正常(只要我不必发送数据)。
采纳答案by R. Oosterholt
you need to serialize your json, try:
您需要序列化您的 json,请尝试:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})