JSON.stringify() - 嵌套对象

时间:2013-10-29 00:32:48

标签: ajax json object stringify

在嵌套对象上使用JSON.stringify()的正确方法是什么?我从一个需要JSON字符串的api调用中得到一个错误的请求:

testData = {"credentials": {"user": "test@email.com", "password": "testpassword", "country": "us"}};

当我查看postDasta时:

"{"credentials": {"user": "test@email.com", "password": "testpassword", "country": "us"}}";

$.ajax({
    ...
    data: JSON.stringify(testData),
    ...
});

谢谢,

Ĵ

3 个答案:

答案 0 :(得分:2)

我正在寻找的答案是:You need to use JSON.stringify to first serialize your object to JSON, and then specify the content-type so your server understands it's JSON.

因此,如果服务器需要JSON,则需要contentType和stringify。

答案 1 :(得分:1)

如果这是jQuery(它看起来像是),data参数接受一个对象并执行必要的序列化以将其作为关联数组传递给服务器。如果在传递之前你没有字符串化。

答案 2 :(得分:1)

jQuery的.ajax()方法的data参数不会将json字符串作为值。它需要一个查询形式的字符串(test=value&otherstuff=othervalue)或一个对象,如上面的链接文档中所述。

相关问题