如何将php数组存储在一个cookie中,然后通过javascript读取它


how proper to store php array in one cookie and then read it via javascript?

我需要正确存储php数组,比如说我有一个数组:

$data=array();
$data['test1']="testa";
$data['test2']="testb";
$data['test3']="testc";
$data['test4']="testd";

我通过php:存储它

setcookie("data","test1=testa;test2=testb;test3=testc;test4=testd;",time()+(60)*(60));

但是当我需要通过javascript读取它时,里面的值显示为test1%3Dtesta%3Btest2%3Dtestb%3Btest3%3Dtestc%3Btest4%3Dtestd%3B

为什么逃跑了吗?

此外,我不知道如何用javascript正确地阅读它,我想检查cookie数组值是否已设置,然后写入网站:使用document.write()函数与php中的方式相同:echo$data['test1'],但使用javascript语言。

为什么;都逃走了

http://curl.haxx.se/rfc/cookie_spec.html

NAME=VALUE此字符串是一系列字符,不包括分号、逗号和空白。

Unescape

document.write(
  unescape("test1%3Dtesta%3Btest2%3Dtestb%3Btest3%3Dtestc%3Btest4%3Dtestd%3B")
);
encodeURIComponent('foo;bar') == "foo%3Bbar"
decodeURIComponent("foo%3Bbar") == 'foo;bar';

阅读Cookie JS

document.cookie-http://www.quirksmode.org/js/cookies.html

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}