在js的Cookie php

时间:2017-09-01 10:51:58

标签: php json cookies setcookie

如果php创建cookie无法在js中使用它们。 创建cookie:

function opo_setcookie( $name, $value, $expire = 0, $secure = false ) {
        if ( ! headers_sent() ) {
            setcookie( $name, $value, $expire, COOKIEPATH ? COOKIEPATH : '/', COOKIE_DOMAIN, $secure );
        } elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
            headers_sent( $file, $line );
            trigger_error( "{$name} cookie cannot be set - headers already sent by {$file} on line {$line}", E_USER_NOTICE );
        }
    }
...
$cart = array("key"=>$key, "user"=> $user, "products"=> array(), "total"=> 0, "price"=>0, "lang"=>ICL_LANGUAGE_CODE);
opo_setcookie('opo_cart', addslashes( json_encode($cart) ), time()+2592000);

尝试获取cookie:

function getCookie(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;
    }
var json_str = getCookie('opo_cart');

但得到错误:未捕获的SyntaxError:位于0的JSON中出现意外的标记%。 因为cookie的含量为&#34;%7B%5C%22lang%5C%22%3A%5C%22en%5C%22%7D ...&#34; 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您需要使用decodeURI函数:

var json_str = decodeURI(getCookie('opo_cart'));

见这里:https://www.w3schools.com/jsref/jsref_decodeuri.asp