Serializing a JSON Data Packet in JQuery AJAX POST

I have a data structure like socket

var s = { "a": "foo", "b": 5, "c": {"d": "a long string"}, "e": { "f": { "g": { "h": [1, 0, -2.1, 1.43] } }, "i": { "j": { "k": [-3.2, 3.003, 0, 0] } } } }; 

I want to save the keys "a", "b", "c" and "e" of the variable s in the database table so that I can restore them again. I am posting s via jQuery AJAX POST. Values ​​will be inserted and saved as plain text (except for "b", which is always a number).

 ajax: { url: uri, type: "POST", data: s, dataType: "json", success: function(data, status) { .. } } 

Here is the problem I am facing. In Firebug, I see my message options ... they are really messed up. It looks like the data was serialized at the level of each element (like deep serialization), while I was hoping for something like

 e={"f":{"g":{"h":[1,0,-2.1,1.43]}},"i":{"j":{"k":[-3.2,3.003,0,0]}}} 

Update : instead, I get the following (I have an unescaped line below, so it is more readable)

 a=foo&b=5&c[d]=a long string&e[f][g][h][]=1&e[f][g][h][]=0&e[f][g][h][]=-2.1&e[f][g][h][]=1.43 

Maybe I'm doing it wrong, so feel free to guide me on a better path.

+7
source share
1 answer

Use the JSON.stringify method to serialize the data object into a string and send it. On the server side, just save it as it is in your database. try it

 ajax: { url: uri, type: "POST", data: { data: JSON.stringify(s) }, dataType: "json", success: function(data, status) { .. } } 

Almost all modern browsers support JSON natively. For browsers that don't have it natively, you can enable the required js from http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js

+9
source

All Articles