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

hxzsmxv2  于 2022-12-18  发布在  jQuery
关注(0)|答案(2)|浏览(283)

我有以下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,“状态文本”:“错误请求”
“客户端发送的请求语法不正确。”
服务器运行的是Spring-MVC。但是据我所知,它工作正常。因为如果我用Postman手动发送请求,下面的配置可以工作。
标题:

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

内容:

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


我不得不提到这是一个跨域请求(在开发过程中,它将被托管在与服务器相同的域中)。我确实禁用了浏览器中的安全设置,对服务器的 AJAX 请求工作正常(只要我不必发送数据)。

5ktev3wc

5ktev3wc1#

你需要序列化你的json,尝试:

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

lymnna712#

JSON.stringify()方法用于将javascript对象转换为json字符串。您需要拥有此方法。此外,最好在AJAX中包含成功和错误部分。

$.ajax({
    type: 'POST',
    url : 'http://awesome-url',
    crossDomain: true,
    data: JSON.stringify(user), // turn a javascript object into json string
    contentType:'application/json; charset=utf-8',
    dataType: 'json',
    success: function (html) {
            alert(html);
    }, error: function (error) {
            alert(error);
    }
})

相关问题