Reputation: 29267
I have this Javascript data:
[{id:123,type:"test"},{id:154,type:"another"}]
How would you transform that into something so that I can pass it as a HTTP post request?
menu[0][id] = 123
menu[0][type] = test
menu[1][id] = 154
menu[1][type] = another
I dont want to pass the actual JSON data, I want to clean it up and pass it as formatted HTTP paramaters.
EDIT
Was able to parse the object on the client side using something like this, maybe you guys would suggest something better before I sign this as "answered"?
this.serialize = function(elem) {
var childs = elem.childElements();
var str = "";
for(var i=0, item; i<childs.length; i++) {
item = childs[i];
str += ((i)?"&":"")+"menu[" + i +"][id]=" + item.id.replace(/item_/,"");
str += "&menu[" + i +"][type]=" + item.className;
str += "&menu[" + i +"][section]=" + elem.id;
str += "&menu[" + i +"][position]=" + i;
}
return str;
}
Upvotes: 0
Views: 6286
Reputation: 19344
"?qsparam=" + escape("[{id:123,type:'test'},{id:154,type:'another'},...]")
Upvotes: 0
Reputation: 488434
var data = [{id:123,type:"test"},{id:154,type:"another"}];
var params = new Array();
for(var x = 0; x < data.length; x++) {
params.push("id=[" + x + "]=" + escape(data[x].id));
params.push("type=[" + x + "]=" + escape(data[x].type));
}
alert(params.join("&")); // output: id=[0]=123&type=[0]=test&id=[1]=154&type=[1]=another
Is that what you want?
Upvotes: 3
Reputation: 75427
I believe HTTP POST only accepts a flat key/value collection, not any arbitrary JavaScript data structure.
If you can flatten it (for example, like John Stauffer shows), and if you're posting to your own domain, you can use an XMLHttpRequest
to post and pass the key/value collection, formatted like a query string, with the .send(data) method.
If you don't want to implement it yourself most JavaScript libraries should have an implementation (e.g. jQuery.post).
Upvotes: 0
Reputation: 16360
menu0.id=123&menu0.type=test&menu1.id=154&menu1.type=another
This is fairly easy to parse on the server, in that it's a regular format.
Upvotes: 0