2013-10-29 312 views
0

在嵌套对象上使用JSON.stringify()的正确方法是什么?我收到来自API调用一个坏的请求预计JSON字符串:JSON.stringify() - 嵌套对象

testData = {"credentials": {"user": "[email protected]", "password": "testpassword", "country": "us"}}; 

当我查看postDasta:

"{"credentials": {"user": "[email protected]", "password": "testpassword", "country": "us"}}"; 

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

感谢,

Ĵ

+0

您是否尝试过将对象传递给数据而不进行字符串化?我不记得数据参数期望一个字符串。据我所知,它要么是一个对象,要么是一个字符串来代替get请求。 – Daedalus

回答

1

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

+0

如果我放弃contentType:'application/json'我得到:'415 Unsupported Media Type - 30ms - 752B)'。当我使用休息客户端时,请求可以很好地使用'{“credentials”:{“user”:“[email protected]”,“password”:“testpassword”,“country”:“us”}}'。 – neridaj

+0

@neridaj如果您不回复我的回答,您如何能期待我回复? – Daedalus

1

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

+0

我删除了JSON.stringify()并验证了我通过$ .isPlainObject(testData):true发送了一个对象。当我查看postData时,它看起来像一个url编码查询字符串:“credentials%5Buser%5D = test%40email.com&credentials%5Bpassword%5D = testpassword&credentials%5B&credentials%5Bcountry%5D = us”,但contentType设置为'application/json '和类型设置为'发布'。 – neridaj

+0

var testData = {“credentials”:{“user”:“[email protected]”,“password”:“testpassword”,“country”:“us”}}; $阿贾克斯({ \t \t \t \t网址: '/凭据', \t \t \t \t类型: '后', \t \t \t \t的contentType: '应用/ JSON', 成功:功能(数据,textStatus, jqXHR){ \t \t \t \t警报( '成功');} , \t \t \t \t数据:TESTDATA, \t \t \t \t错误:功能(jqXHR,textStatus,errorThrown){ \t \t \t \t警报( '错误'); \t \t \t \t \t \t} });' – neridaj

+0

你不应该设置内容类型为application/JSON。我真的没有理由使用它,除非你专门发送json。如文档中所述,它将任何json对象转换为查询字符串,以便它可以被服务器转换为post请求(这是自动完成的),例如..不修改内容类型,它可以通过'$ _POST'。 – Daedalus