【发布时间】:2016-11-30 18:38:53
【问题描述】:
我正在尝试发送一个看起来像这样的对象
var postBody = {
id: userID,
objectID: [0, 1],
objects: [
{id: 0, x: 0.33930041152263374, y: 0.08145246913580247, width: 0.0823045267489712, height: 0.30864197530864196},
{id: 1, x: 0.5277777777777778, y: 0.08453888888888889, width: 0.0823045267489712, height: 0.30864197530864196}
]
};
这是 ajax 调用
$.ajax({
type: 'POST',
url: url,
data: postBody,
dataType: 'JSONP',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
});
这就是它在服务器上的样子
{ id: '583f137fc338b517ec467643',
'objectID[]': [ '0', '1' ],
'objects[0][id]': '0',
'objects[0][x]': '0.33930041152263374',
'objects[0][y]': '0.08145246913580247',
'objects[0][width]': '0.0823045267489712',
'objects[0][height]': '0.30864197530864196',
'objects[1][id]': '1',
'objects[1][x]': '0.5277777777777778',
'objects[1][y]': '0.08453888888888889',
'objects[1][width]': '0.0823045267489712',
'objects[1][height]': '0.30864197530864196' }
如果我输入数据:JSON.stringify(postBody) 这就是我得到的
{ '{"id":"583f137fc338b517ec467643","objectID":[0,1],"objects":[{"id":0,"x":0.5,"y":0.5,"width":0.1,"height":0.1},{"id":1,"x":0.5401234567901234,"y":0.1833043209876543,"width":0.0823045267489712,"height":0.30864197530864196}]}': '' }
而且它有效!但后来我不能 JSON.parse() 它 这就是我尝试时得到的结果
TypeError: Cannot convert object to primitive value
我在后端数据上所做的就是这个
console.log(JSON.parse(req.body)); // in the first example it was the same thing but only without JSON.parse()
有人知道为什么会发生这种情况吗? 即使你对我可以尝试在这里发布的内容有任何建议,否则我将不得不编写一个函数来解析这些糟糕的输入,哈哈。
【问题讨论】:
-
我认为您尝试对
JSON.parse的响应已经是服务器返回的json 对象。你可以发布服务器的回复吗? -
@Lex - 我认为你是对的,取决于 op 的服务器设置 - 响应已经是
object
标签: javascript jquery json ajax node.js