Do you know a fast and simple way to encode a javascript object into a string that I can pass via GET?
No jQuery, no other frameworks, just plain Javascript :)
Do you know a fast and simple way to encode a javascript object into a string that I can pass via GET? No jQuery, no other frameworks, just plain Javascript :) |
|||
|
like this?
Edit: this one also converts recursive objects (using php "array" notation for the query string)
|
|||||||||||||||||||||
|
jQuery has a function for this, if you're already using it u can use that: http://api.jquery.com/jquery.param/ |
|||
A small amendment to the accepted solution by user187291:
Checking for hasOwnProperty on the object makes JSLint/JSHint happy, and it prevents accidentally serializing methods of the object or other stuff if the object is anything but a simple dictionary. See the paragraph on for statements in this page: http://javascript.crockford.com/code.html |
|||
|
|
|||
|
Here's the coffeescript version of accepted answer. This might save time to someone.
|
|||||
|
use JSON. take a look at this question for ideas on how to implement. |
|||||||||||||
|
Do you need to send arbitrary objects? If so, GET is a bad idea since there are limits to the lengths of URLs that user agents and web servers will accepts. My suggestion would be to build up an array of name-value pairs to send and then build up a query string:
|
|||
|
If you want to convert a nested object recursively and the object may or may not contain arrays (and the arrays may contain objects or arrays, etc), then the solution gets a little more complex. This is my attempt. I've also added some options to choose if you want to record for each object member at what depth in the main object it sits, and to choose if you want to add a label to the members that come from converted arrays. Ideally you should test if the thing parameter really receives an object or array.
|
|||
|
Just another way (no recursive object):
|
|||
|
ok, it's a older post but i'm facing this problem and i have found my personal solution.. maybe can help someone else..
|
|||
|