如何在php中编码数组,将其保存为cookie,在js中编辑并再次保存
How to encode array in php, save it an a cookie, edit it in js and save it again?
标题几乎说明了我想要做什么。我有一个php数组,我需要编码和保存在一个cookie,然后我想读取和编辑它使用js和保存回来。
这是我到目前为止所尝试的,但没有结果
file.php
$arrayToEncode = array("test" => true, "test2" => false);
setcookie("cookiename", json_encode($arrayToEncode), time() + 365 * 24 * 60 * 60, '/');
jsfile.js
// readCookie is a function that given the key of the cookie it returns the value of it
var cookieArray = JSON.parse(readCookie("announcements"));
cookieArray["test"] = false;
console.log(cookieArray);
我得到的是jsfile
第一行的错误Uncaught SyntaxError: Unexpected token %
非常感谢你的帮助:)
编辑:从php添加的cookie值是% 3一7 b % 22个测试% 22% % 2 c % 22 test2 % 22% 3 afalse % 7 d
你需要解码从cookie
得到的字符串console.log(jQuery.parseJSON(decodeURIComponent(cookie)));
似乎是正确的-除了一个简单的语法错误:
$arrayToEncode = array("test" => true, "test2 => false);
忘记关闭引号
"test2" => false
我想问题出在readCookie()
.
用这个插件代替:
https://github.com/carhartl/jquery-cookie 使用上面的插件 var cookieValue = JSON.parse($.cookie("cookiename"));
$.removeCookie("cookiename");
cookieValue['test'] = false;
$.cookie.json = true;
$.cookie("cookiename", cookieValue, { expires : 10 });
初始值:%7B%22test%22%3Afalse%2C%22test2%22%3Afalse%7D
更新值:%7B%22test%22%3Atrue%2C%22test2%22%3Afalse%7D
相关文章:
- 如何使用 Angular JS 将数据保存在数据库中
- 使用History.js保存显示的igGrid列
- Three.js保存修改后的网格顶点r67
- 保存leaflet.js的当前视图
- AJAX将JSON数组保存到多个JS变量中
- 如何使用heatmap.js保存canvas标记生成的图像文件
- d3.js保存状态
- 将表单对象保存到具有主干.js的模型
- Angular js,在选择元素上,我想 POST 数据以将其保存在数据库中,然后我想使用 PUT 更新它而无需重新加载
- 如何抓取本地保存的 html 的“隐藏”JS
- 如何使用office.js检查未保存文件的具体文件扩展名
- 如何保存和设置窗口.pageYOffset with shadowbox.js.
- 如何在ruby on rails中保存和发布Webgl中的JS代码结果
- 有没有一种方法可以保存单个图像,并防止用户使用dropzone.js放置多个图像
- 如何在PHP站点上保存JS变量值
- GRAILS保存JS文件
- 函数保存JS对象不工作
- 保存JS对象到Knockout Array
- 如何设置CodeKit 2在保存JS文件时自动更新HTML页面?
- 用于保存JS对象字面量文件的约定