views:

1996

answers:

4

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;
}
A: 

"?qsparam=" + escape("[{id:123,type:'test'},{id:154,type:'another'},...]")

Tracker1
You might have miss understood my question, anyhow that is wrong anyhow, I dont want to pass the actual JSON data, I want to clean it up and pass it as formatted HTTP paramaters.
Luca Matteis
A: 

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.

John Stauffer
A: 

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).

orip
+2  A: 
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?

Paolo Bergantino
oh nice, thanks, similar to my solution, I'll mark you ask fixed.
Luca Matteis
Be careful, you shouldn't iterate javascript arrays using the for(x in obj).. I believe it breaks in IE, use the for(var i=0 ...);
Luca Matteis
Doesn't it only break if people messed with the prototype?
Paolo Bergantino
I know it breaks if the "prototype" library is loaded.
krosenvold