Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top