如何在php中编码数组,将其保存为cookie,在js中编辑并再次保存

How to encode array in php, save it an a cookie, edit it in js and save it again?

本文关键字:保存 js cookie 编辑 php 编码 数组      更新时间:2023-09-26

标题几乎说明了我想要做什么。我有一个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