What's the proper way to use JSON.stringify() on nested objects? I'm getting a bad request from a api call that expects a JSON string:

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

when I view the postDasta:

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

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

Thanks,

J

有帮助吗?

解决方案

The answer I was looking for was: 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.

So, contentType and stringify are necessary if the server is expecting JSON.

其他提示

If this is jQuery (it looks like it is), the data parameter accepts an object and performs the necessary serialization to pass it as an associative array to the server. You don't stringify if before passing it.

The data parameter for jQuery's .ajax() method does not take a json string as value. It either expects a query-formed string(test=value&otherstuff=othervalue), or an object, as noted in the linked documentation above.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top