I'm populating an array nodevalues
with objects. It looks like this:
nodevalues.push({id: this.id, left: left, right: right});
This line is inside a $.each()
iterator which iterates over some li
nodes and also calculates the left
and right
values.
So I have an array with several objects who all look the same:
Is it possible to serialize this array to an url string for database storage using jQuery.post()
?
Calling $(nodevalues).serialize()
returns nothing and $.param(nodevalues)
returns undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined
...
I'm populating an array nodevalues
with objects. It looks like this:
nodevalues.push({id: this.id, left: left, right: right});
This line is inside a $.each()
iterator which iterates over some li
nodes and also calculates the left
and right
values.
So I have an array with several objects who all look the same:
Is it possible to serialize this array to an url string for database storage using jQuery.post()
?
Calling $(nodevalues).serialize()
returns nothing and $.param(nodevalues)
returns undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined
...
-
3
Never do
$(this).attr('id')
. "this" is .each() is the DOM element ->this.id
– Didier Ghys Commented Nov 30, 2011 at 11:15 - @Didier G I'm not sure I understand your ment. $(this) in jquery is this[0] in javascript. You should ALWAYS use $(this).attr('id') in jquery. – Thomas Clayson Commented Nov 30, 2011 at 11:16
- @DidierG. I think you're missing the point of my post. My question is how to serialize an array of objects. The code you mention works like it should. – netiul Commented Nov 30, 2011 at 11:18
- @ZacL. It's just a ment, not an answer to your problem, i'm aware of that. – Didier Ghys Commented Nov 30, 2011 at 11:23
- @ThomasClayson. Check this example – Didier Ghys Commented Nov 30, 2011 at 11:24
3 Answers
Reset to default 12jQuery.param() might do what you want
var dataString = jQuery.param(nodevalues);
It seems that param only works on objects, not arrays.
If you wrap your array in an object it works fine:
var nodevalues = [];
nodevalues.push({id: "node1", left: 1, right: 20});
nodevalues.push({id: "node2", left: 2, right: 10});
nodevalues.push({id: "node3", left: 3, right: 30});
nodevalues.push({id: "node4", left: 4, right: 40});
var data = { data: nodevalues };
alert($.param(data));
http://jsfiddle/4NELt/
You could use the stringify function from the JSON library.
you can supply the data as second argument to jquery.post()
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] );
jquery will serialize it for you.