Reputation: 15
I have seen at several places developers are using JSON.stringify(data)
while making an Ajax call to the server for the serialization of post data in JSON string, but why it is needed ?
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Upvotes: 0
Views: 245
Reputation: 2523
Several modern frameworks are capable to directly bind JSON data structures to their model businesses, this allows for a incredibly fast and easy relationship between client and server data models.
This way you can work feely on your client side with js objects, on the moment that you send data to the server via AJAX, you just stringify these objects to allow the server end to understand them, and in an automatic way your server will be able to translate that info to your server data classes, without further interaction needed (of course, you will need defined classes that are compatible with your client model data structures).
Upvotes: -1
Reputation: 944149
You have to encode the data using some method in order to send it over HTTP.
JSON is a standard format that supports common data structures like arrays. This lets you describe most kinds of data that you would want to send.
Upvotes: 2