如何正确地使用javascript阅读php cookies

时间:2015-11-15 19:35:26

标签: javascript php cookies

考虑这个php和javascript代码:

<i>

然后我在控制台中看到的是: __utma = 111872281.291759993.1444771465.1445374822.1445436904.4; __utmz = 111872281.1444771465.1.1.utmcsr =(直接)| utmccn =(直接)| utmcmd =(无); PHPSESSID = 8572f606897b1732c31a25dee29ca077

我想在javascript中使用$ _COOKIE [&#39; test&#39;]的值...但这个奇怪的字符串对我没用。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

<?php
$cookie_name = "test";
$cookie_value = "123";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>

你需要像这样编写你的PHP代码

您可以使用此脚本如果您想要特定的cookie

<script>
function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

console.log(getCookie('test'));
<script>