“400 Bad Request”响应AJAX请求 [英] "400 Bad Request" response for AJAX request
问题描述
我有以下jQuery AJAX请求:
I have the following jQuery AJAX request:
// 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));
});
服务器的响应是:
status:400,statusText:错误请求
客户端发送的请求在语法上不正确。
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
服务器正在运行Spring-MVC。但据我所知,它的工作正常。因为如果我使用Postman手动发送请求并且以下配置可行。
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.
标题:
Content-Type application/json; charset=utf-8
内容:
{"firstname":"alex","lastname":"lala","role":"admin"}
我必须提到它是一个跨域请求(在开发时,它将与服务器托管在同一个域中)。我确实禁用了浏览器中的安全设置,并且对服务器的AJAX请求工作正常(只要我不必发送数据)。
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).
推荐答案
你需要序列化你的json,试试:
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
这篇关于“400 Bad Request”响应AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!