问题描述
考虑以下php和javascript代码:
consider this php and javascript code :
<?php $_COOKIE['test']='123'; ?>
<script>console.log(document.cookie);</script>
然后我在控制台中看到的是:__utma = 111872281.291759993.1444771465.1445374822.1445436904.4;__utmz = 111872281.1444771465.1.1.utmcsr =(直接)| utmccn =(直接)| utmcmd =(无);PHPSESSID = 8572f606897b1732c31a25dee29ca077
then what i see in console is :__utma=111872281.291759993.1444771465.1445374822.1445436904.4; __utmz=111872281.1444771465.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=8572f606897b1732c31a25dee29ca077
我想在javascript中使用$ _COOKIE ['test']的值,但是这个奇怪的字符串对我没有用.我该怎么办?
i want to use the value of $_COOKIE['test'] in javascript ... but this strange string is not useful for me . how can i do that ?
推荐答案
<?php
$cookie_name = "test";
$cookie_value = "123";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
您需要这样编写php代码
You need to write your php code like this
如果您想要特定的cookie,则可以使用此脚本
You can use this script If u can want particular 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>
这篇关于如何正确使用javascript阅读php cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!