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

时间:2014-08-04 12:56:16

标签: javascript php jquery cookies

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

中第一行的错误
  

未捕获的SyntaxError:意外的标记%

非常感谢您的帮助:)

编辑:从php添加的cookie值是

  

%7B%22test%22%3Atrue%2C%22test2%22%3Afalse%7D

3 个答案:

答案 0 :(得分:0)

似乎正确 - 除了简单的语法错误:

$arrayToEncode = array("test" => true, "test2 => false);

您忘了关闭引号

"test2" => false

答案 1 :(得分:0)

你必须解码从cookie

获得的字符串
console.log(jQuery.parseJSON(decodeURIComponent(cookie)));

答案 2 :(得分:0)

我认为问题出在readCookie()

请改用此插件:

https://github.com/carhartl/jquery-cookie

JS使用上面的插件

    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