简体   繁体   中英

JavaScript/PHP cookie serialization methods?

I have a form which I would like to store the values of in a cookie so the user doesn't have to re-enter the form every visit. (The form is a few selects to filter search results.)

I would like for the cookie serialization to easily be readable from JavaScript (obviously to set the form onLoad ), but I'd also like to be able to read the cookie easily from PHP (so that I can use the form data to filter search results).

How would I go about serializing a form with selects that have multiple="multiple" set into a cookie and have it be easily readable in JavaScript and PHP?

Please don't preach about validation, I'm doing that correctly on the server-side.

If there's a smarter solution to my problem please let me know.

BTW: I'm using CodeIgniter on the server and Prototype/Scriptaculous JavaScript libraries.

Solution: Used Prototype's Object.toJSON( Form.serialize(form, true)) for JavaScript, and used PHP's json_decode(string, bool) to get an associative array in PHP from the JSON.

You could use the JSON format that is already implemented in several languages.

I would recommend YAML. It's basically designed as a common serialization method for several languages, including JavaScript and PHP.

From the YAML site:

YAML was designed to meet the serialization needs of Perl, Python, Ruby, Tcl, PHP, Javascript and Java. It was also designed to be interoperable between those languages. That means YAML serializations produced by Perl can be processed by Python.

Here's a sitepoint article on the topic:

http://www.sitepoint.com/blogs/2004/04/22/serializing-php-data-structures-for-javascript/

The YAML site:

http://www.yaml.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM