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 store the "a", "b", "c", and "e" keys of variable s
in a database table so I can reconstruct them back again. I am sending s
via a jQuery Ajax POST. The values would be inserted and stored as just 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 encountering. In Firebug I can see my post parameters… they are really messed up. Seems like the data have been serialized at the level of each element (kinda like a 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 am getting the following (I have unescaped the string 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
Perhaps I am doing this the wrong way, so feel free to guide me to a better way.
Use JSON.stringify
method to serialize the data object into string and post it. On the server side just store this as is in your DB. Try this
ajax: {
url: uri,
type: "POST",
data: { data: JSON.stringify(s) },
dataType: "json",
success: function(data, status) { .. }
}
Almost all the modern browsers support JSON natively. For browsers which do not have it natively you can include the required js from http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With