发送JSON数据到服务器错误
我想发送一个JSON数据到我的控制器的POST处理程序。我这样做,在我的客户端:发送JSON数据到服务器错误
var userName = $('#userName').val();
var password = $('#password').val();
var mail = $('#mail').val();
var admin =$("#admin").is(':checked');
var user = {userName: userName, password: password, mail: mail, admin:admin};
$.ajax({
async : false,
type:'POST',
url: '/uxiy/webapp/uxmer',
data: user,
dataType: 'json',
success: function(data) {
...
},
error: function(data) {
...
}
});
我的春天控制器如下:
@RequestMapping(method = RequestMethod.POST)
public void createUser(HttpServletResponse response, @RequestBody User user) {
user.setName("POST worked");
//todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
response.setStatus(HttpServletResponse.SC_OK);
}
然而,当我把我的数据我得到这个错误在萤火虫:
"NetworkError: 415 Unsupported Media Type"
是什么错误?
PS: 的萤火虫POST细节的例子:
Parameters application/x-www-form-urlencoded
admin true
mail [email protected]
password r
userName userx
Source
userName=userx&password=r&mail=user%40user.com&admin=true
PS2:当我加入
contentType: 'application/json',
它开始给
"NetworkError: 400 Bad Request"
可能是什么问题,使序列化等?
PS3: 这里:http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/它说:
If there are validation errors, a HTTP 400 is returned with the error messages, otherwise a HTTP 200 is returned.
我有400错误的请求错误。也许问题与此有关?
问题是关于JSON阵列。这不是从客户端发送到服务器的有效JSON字符串。
编辑
为了澄清这一点,我偶然发现了这个帖子。需要在Ajax请求中执行适当的JSON.stringify(data)
。这很奇怪,但是在设置相应的dataType
时,不能通过.ajax
函数完成。
$.ajax({
async : false,
type:'POST',
url: '/uxiy/webapp/uxmer',
data: JSON.stringify(user),
dataType: 'json',
success: function(data) {
...
},
error: function(data) {
...
}
});
您需要设置控制器接受的介质类型。
文档:
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html
在ContentNegotiatingViewResolver
看看的接受:头主要是你需要关注什么。
我新的春天。我用杰克逊Marshaller,但你能给我一个例子如何解决它? – kamaci
将内容类型来application/json
或杰克逊不会踢英寸
$.ajax({
async : false,
type:'POST',
contentType: 'application/json',
url: '/uxiy/webapp/uxmer',
data: user,
dataType: 'json',
success: function(data) {
...
},
error: function(data) {
...
}
});
我跳这个职位将会使画面清晰: http://stackoverflow.com/q/5908466/225396 –