简体   繁体   English

为什么我的cookie不存储?

[英]Why isn't my cookie storing?

I'm trying to set a cookie on a click event to see if a user has actually clicked the respective button. 我正在尝试在click事件上设置cookie,以查看用户是否实际单击了相应的按钮。 The button is as follows: 该按钮如下:

<a href="#/" class="button" id="modalBTN">Click here</a>

My js to set the cookie is: 我的设置cookie的js是:

function setCookie(cname, cvalue, exdays){
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires =" + d.toGMTString();
document.cookie = cname +"="+ cvalue + ";" + expires;
}

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 "";
}

Then, I set the cookie on a click event: 然后,在点击事件中设置Cookie:

$("#modalBTN").click(function(){
    var clicked = "clicked";
    setCookie("clicked", clicked, 30);

    console.log(clicked);
});

My click event works. 我的点击事件有效。 when I console.log(clicked) I see the cookie value, but when I refresh the page the cookie is no longer there. 当我console.log(单击)时,我看到cookie值,但是当刷新页面时,cookie不再存在。

I check it by: 我通过以下方式检查它:

if(getCookie("clicked") != ""){
    //do something else
}

UPDATE 更新

when I call getCookie("otherCookie") it works. 当我调用getCookie(“ otherCookie”)时,它可以工作。 But when I call getCookie("clicked") i get returned null. 但是当我调用getCookie(“ clicked”)时,我返回了null。 Am I only allowed to have one at a time? 我一次只能允许一个吗?

Try this : https://stackoverflow.com/a/24103596/5445351 试试这个: https : //stackoverflow.com/a/24103596/5445351

You can only use console to test the two functions : createCookie & readCookie 您只能使用控制台来测试这两个功能:createCookie和readCookie

Do : createCookie('ppkcookie','testcookie',7); 做: createCookie('ppkcookie','testcookie',7);

Open another page, check if it's still there : 打开另一个页面,检查它是否仍然存在:

var x = readCookie('ppkcookie')
if (x) {
    console.log("ok");
}

Look if it's not your browser that delete cookies automatically. 查看不是您的浏览器自动删除cookie。 I tried with Chrome and IE9. 我尝试使用Chrome和IE9。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM