我有以下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 请求工作正常(只要我不必发送数据)。
2条答案
按热度按时间5ktev3wc1#
你需要序列化你的json,尝试:
lymnna712#
JSON.stringify()
方法用于将javascript
对象转换为json
字符串。您需要拥有此方法。此外,最好在AJAX
中包含成功和错误部分。