I have this data structure:
我有这个数据结构:
var formValues = {
TemporaryToken: a.userStatus.get("TemporaryToken"),
MemorableWordPositionAndValues:[
{
Position: a.userStatus.get("MemorableWordPositions")[0],
Value: this.$('[name="login-memorable-character-1"]').val()
},
{
Position: a.userStatus.get("MemorableWordPositions")[1],
Value: this.$('[name="login-memorable-character-2"]').val()
},
{
Position: a.userStatus.get("MemorableWordPositions")[2],
Value: this.$('[name="login-memorable-character-3"]').val()
}
]
}
And when I send it with $.ajax like so:
当我用$ .ajax这样发送它时:
$.ajax({
url:url,
type:'PUT',
//dataType:"json",
data: JSON.stringify(formValues),
success:function (data) {
}
});
It sends the request. However, if I send it like so:
它发送请求。但是,如果我这样发送:
$.ajax({
url:url,
type:'PUT',
dataType:"json",
data: formValues,
success:function (data) {
}
});
I receive a 400 Bad Request. Is this a problem on the server or is JSON.stringify doing something different to just setting the dataType to 'json'?
我收到400 Bad Request。这是服务器上的问题还是JSON.stringify做了一些不同的事情,只是将dataType设置为'json'?
3 个解决方案
#1
3
The server is expecting a JSON string, not form parameters. JSON.stringify converts your form parameters object/array into a JSON string, which is what your server appears to be expecting.
服务器期望JSON字符串,而不是表单参数。 JSON.stringify将您的表单参数对象/数组转换为JSON字符串,这是您的服务器所期望的。
#2
3
It is still sending the request in the second attempt; it is simply that your server does not understand the request. That is because jQuery automatically processes the formValues data into a query string before sending the data. See the documentation:
它仍在第二次尝试发送请求;只是你的服务器不理解请求。这是因为jQuery在发送数据之前会自动将formValues数据处理为查询字符串。查看文档:
data
数据
Type: Object, String
类型:对象,字符串
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
要发送到服务器的数据。如果不是字符串,它将转换为查询字符串。它附加到GET请求的URL。请参阅processData选项以防止此自动处理。对象必须是键/值对。如果value是一个数组,jQuery会根据传统设置的值使用相同的键序列化多个值(如下所述)。
So, you must use JSON.stringify(), or not use JSON. Note that setting processData to false won't help, since it will simply send the string [object Object] to your server. See also this question.
因此,您必须使用JSON.stringify(),或者不使用JSON。请注意,将processData设置为false将无济于事,因为它只是将字符串[object Object]发送到您的服务器。另见这个问题。
#3
0
What about $.param()?
$ .param()怎么样?
var my_data = {};
my_data.post_name = 'post_value';
$.ajax({
url:'/post_url.php'
data:$.param(my_data);
...
});