js存储cookie,php读取的时候成了乱码 。
问题分析:
这是因为文字编码而造成的,汉字是两个编码,所以才会搞出这么个乱码出来!
解决思路:
1:写入Cookie时,先将其用Url编码,然后再写入
2:当我们读取时再Url解码即可
php两个函数
urlencode()
urldecode()
js两个函数
decodeURI()
encodeURI()
php 设置cookie ,js读取cookie
<?php setcookie ("TestCookie", urlencode("这就是网页21")); ?>
<script type="text/javascript"> alert(decodeURI(getCookie("TestCookie"))) function getCookie(sName) { var aCookie = document.cookie.split('; '); for (var i=0; i < aCookie.length; i++) { var aCrumb = aCookie[i].split('='); if (sName == aCrumb[0]) return decodeURI(aCrumb[1]); } return ''; } </script>
js设置cookie php读取cookie
<script type="text/javascript">function setCookie(name, value, time){ var nameString = name + '=' + encodeURI(value); var expiryString = ""; if(time !== 0) { var expdate = new Date(); if(time == null || isNaN(time)) time = 60*60*1000; expdate.setTime(expdate.getTime() + time); expiryString = ' ;expires = '+ expdate.toGMTString(); } var path = " ;path =/"; document.cookie = nameString + expiryString + path; }setCookie("TestJsCookie", "我是中国人", 0) </script>
<?php echo urldecode($_COOKIE["TestJsCookie"]); ?>