简体   繁体   English

JavaScript/PHP cookie 序列化方法?

[英]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.我有一个表单,我想将它的值存储在 cookie 中,这样用户就不必每次访问都重新输入表单。 (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).我希望可以从 JavaScript 轻松读取 cookie 序列化(显然是设置表单onLoad ),但我也希望能够从 PHP 轻松读取 cookie(这样我就可以使用表单数据来过滤搜索结果)。

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?我将如何 go 关于序列化具有multiple="multiple"设置到 cookie 中的选择的表单并使其在 JavaScript 和 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.顺便说一句:我在服务器上使用 CodeIgniter 和 Prototype/Scriptaculous JavaScript 库。

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. 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.您可以使用已经以多种语言实现的JSON 格式

I would recommend YAML.我会推荐 YAML。 It's basically designed as a common serialization method for several languages, including JavaScript and PHP.它基本上被设计为几种语言的通用序列化方法,包括 JavaScript 和 PHP。

From the YAML site:从 YAML 网站:

YAML was designed to meet the serialization needs of Perl, Python, Ruby, Tcl, PHP, Javascript and Java. 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.这意味着由 Perl 生成的 YAML 序列化可以由 Python 处理。

Here's a sitepoint article on the topic:这是关于该主题的站点点文章:

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

The YAML site: YAML 站点:

http://www.yaml.org/ http://www.yaml.org/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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