我正在尝试在 wordpress 页面加载时设置 Cookie。不幸的是,当我添加下面的脚本代码时,什么也没有发生。我一直在 php setcookie("gmp_", "1", strtotime( '+30 days' ), '/');
中使用这段代码没有问题,但现在我正在尝试让 Javascript 版本工作。我是不是忽略了什么?
<script type="text/javascript">
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
setCookie('gmp_','1',30);
</script>
最佳答案
注意;后面的空格 split 。
function ReadCookie()
{
var allcookies = document.cookie;
alert("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split('; '); //notes the space after ;
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
关于javascript - 使用 Javascript 设置 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28574685/