【问题标题】:Cant send Object with property that has array of objects无法发送具有对象数组的属性的对象
【发布时间】: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


【解决方案1】:

所有的解析/字符串化都由 Node 处理,所以不用担心,只需按原样传递您的对象,您就可以在 req.body 中访问它的属性。

客户:

$.ajax({
            type: 'POST',
            url: url,
            data: postBody,
            dataType: 'json',
            success: function(data) {
                console.log(data);
            },
            error: function(err) {
                console.log(err);
            }
        });

服务器:

 console.log(req.body);  //should give you [Object object]

然后您可以将其发送回:res.status(200).json(req.body));

并在您的 ajax 回调中读取它:

success: function(data) {
    console.log(data);
},

【讨论】:

    猜你喜欢
    • 2020-10-15
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2015-12-14
    • 1970-01-01
    相关资源
    最近更新 更多