将JSON数据发送到服务器错误 [英] Sending JSON Data to Server Error
问题描述
我想将JSON数据发送到控制器的POST处理程序.我是在客户端这样做的:
I want to sent a JSON data to my controller's POST handler. I do that at my client side:
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) {
...
}
});
我的Spring控制器如下:
My Spring controller as follows:
@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);
}
但是,当我发送数据时,在Firebug上出现了该错误:
However when I send my data I get that error at Firebug:
"NetworkError:415不支持的媒体类型"
"NetworkError: 415 Unsupported Media Type"
怎么了?
PS: Firebug POST详细信息的示例:
PS: An example of Firebug POST details:
Parameters application/x-www-form-urlencoded
admin true
mail user@user.com
password r
userName userx
Source
userName=userx&password=r&mail=user%40user.com&admin=true
PS2: 在我添加
contentType: 'application/json',
它开始给予
"NetworkError: 400 Bad Request"
可能是什么问题,进行序列化等?
What can be the problem, making serialization, etc?
PS3: 此处: http://blog.springsource. com/2010/01/25/ajax-simplifications-in-spring-3-0/它说:
如果存在验证错误,则会返回HTTP 400和 错误消息,否则返回HTTP 200.
If there are validation errors, a HTTP 400 is returned with the error messages, otherwise a HTTP 200 is returned.
我遇到400错误的请求错误.也许问题与此有关?
I have 400 Bad Request Error. Maybe the problem is related to that?
推荐答案
问题与JSON数组有关.这不是从客户端发送到服务器的有效JSON字符串.
Problem was about the JSON array. It was not a valid JSON string that was sent from client to server.
编辑
为了澄清这一点,我偶然发现了这篇文章.需要在Ajax请求中执行正确的JSON.stringify(data)
.奇怪,但是在设置相应的dataType
时.ajax
函数无法完成.
To clarify this, I stumbled upon this post. It is required to do a proper JSON.stringify(data)
in the Ajax request. It's strange but it's not done by the .ajax
function when setting the corresponding dataType
.
$.ajax({
async : false,
type:'POST',
url: '/uxiy/webapp/uxmer',
data: JSON.stringify(user),
dataType: 'json',
success: function(data) {
...
},
error: function(data) {
...
}
});
这篇关于将JSON数据发送到服务器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!