首先我知道有很多问题和我的类似。当然我已经全部阅读了,但我找不到解决方案或不明白如何解决我的问题。 这是主要问题:我在 java 脚本中有一个关联数组,我想将它序列化并将其保存在 cookie 中,然后我想通过使用 unserialize 方法用 php 读取这个 cookie。所以我找不到序列化关联数组的正确方法。
有javascript
function renewCookie(){
var myArray = {radius: radius, type:type, date:price, name:company}
serializeValue = JSON.stringify(myArray);/* i used this serialize function that i found on web http://phpjs.org/functions/serialize/ but it didn't work.*/
createCookie('parameters',serializeValue ,999);
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
有php
<?php
if (isset($_COOKIE["parameters"])){
$UserParam = json_decode($_COOKIE["parameters"]);/*I unserialize the cookie because i suppose that it is serialized*/
echo"<script>function readCookie(){ getLocationFunction(".$UserParam["radius"].",\"".$UserParam["type"]."\",\"".$UserParam["date"]."\",\"".$UserParam["name"]."\")}</script>";
}
else{setcookie("parameters","$defaultParam",time()+3600);}
?>
有人知道如何用 php 读取由 javascript 创建的 cookie 吗?我还解释说我有一个关联数组,因为我想同时拥有多值 cookie 和键的名称。请帮助我提供一些代码。如果您需要更多解释,请询问。提前致谢!!
更新:上面的代码可以很好地满足您的建议,但它只适用于 firefox 和 chrome,不适用于 opera、safari 和 explorer。有人看到我做错了什么了吗??
最佳答案
只需使用 JSON 序列化。
在 JavaScript 中:
serializeValue = JSON.stringify(myArray);
在 PHP 中
$UserParam = json_decode($_COOKIE["parameters"]);
请注意,在这种情况下,$UserParam
将在对象上。如果你想强制使用关联数组:
$UserParam = json_decode($_COOKIE["parameters"], true);
关于php - 如何使用 javascript 序列化关联数组并将其保存在 cookie 中,然后使用 php 读取它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16045506/