AJAX请求的“ 400错误请求”响应


问题内容

我有以下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));
});

服务器的响应为:

“”状态“:400,” statusText“:”错误的请求“
”客户端发送的请求在语法上不正确。

服务器正在运行Spring-MVC。但据我所知,它工作正常。因为如果我使用Postman和以下配置手动发送请求,则它可以正常工作。

标头:

Content-Type application/json; charset=utf-8

内容:

{"firstname":"alex","lastname":"lala","role":"admin"}

我不得不提到,这是一个跨域请求(在开发时,它将稍后与服务器托管在同一域中)。我确实禁用了浏览器中的安全设置,并且向服务器的AJAX请求运行正常(只要我不必发送数据即可)。


问题答案:

您需要序列化json,请尝试:

$.ajax({
    type: 'POST',
    url : 'http://awesome-url',
    crossDomain: true,
    data: JSON.stringify(user),
    contentType:'application/json; charset=utf-8',
    dataType: 'json'
})