简体   繁体   中英

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

I need to store php array properly, lets say I have array of:

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

i'm storing it via php:

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

but when i need to read it via javacript, values inside shows as test1%3Dtesta%3Btest2%3Dtestb%3Btest3%3Dtestc%3Btest4%3Dtestd%3B

why ; are escaped?

Also i have no idea how to read it proper way with javascript, I want to check that cookie array value is set, then write to the website: with document.write(); function the same as way as it would be in php: echo $data['test1']; but in javascript language.

Why ; are escaped?

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

NAME=VALUE This string is a sequence of characters excluding semi-colon, comma and white space.

Unescape

document.write(
  unescape("test1%3Dtesta%3Btest2%3Dtestb%3Btest3%3Dtestc%3Btest4%3Dtestd%3B")
);

encodeURIComponent('foo;bar') == "foo%3Bbar"
decodeURIComponent("foo%3Bbar") == 'foo;bar';

Read 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM