[英]Using Cookies to set an alert in javascript
I'm trying to create a script that when the user opens the site he or she will be welcomed by a prompt and after an alert will say welcome but also what is entered in the prompt will set a cookie for 1 minute the problems I'm facing are: 我正在尝试创建一个脚本,当用户打开网站时,他或她将受到提示的欢迎,并且在警报提示后将显示“欢迎”,但在提示中输入的内容也会将Cookie设置为1分钟,这是我遇到的问题我面临的是:
1. The alert does not show up 1.警报不显示
2. The Cookie will not set 2. Cookie不会设置
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="") {
alert("Welcome again "+ username);
}
else {
username=prompt("Please input name:","");
if (username !=null && username!="") {
setCookie("username", username, 365);
}
else {
alert("Error");
}
}
}
function setCookie (cname,cvalue,exdays)
{
var d = new Date();
d.setTime (d.getTime()+ (10*1000));
var expires ="; expires= "+ d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires; +"; path /";
}
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 "";
}
Try replacing var expires ="; expires= "+ d.toGMTString();
尝试替换
var expires ="; expires= "+ d.toGMTString();
with var expires ="; expires= "+ d.toUTCString();
使用
var expires ="; expires= "+ d.toUTCString();
The expire time is saved as Unix timestamp. 到期时间另存为Unix时间戳。
Edit: You need to execute the function checkCookie too. 编辑:您也需要执行功能checkCookie。 I thought that was obvious.
我认为这很明显。
https://jsfiddle.net/osgohu5b/ https://jsfiddle.net/osgohu5b/
Here is a jsfiddle of your code: https://jsfiddle.net/19yp8ucd/3/ . 这是您的代码的jsfiddle: https ://jsfiddle.net/19yp8ucd/3/。 It works fine.
工作正常。 You just need to call checkCookie() function.
您只需要调用checkCookie()函数。
checkCookie();
See the last line in .js of the fiddle. 请参见小提琴.js的最后一行。
Also, you're not using the number of days in your setCookie() function. 另外,您没有在setCookie()函数中使用天数。 You can check a good implementation of setCookie(), getCookie(), eraseCookie() here: https://stackoverflow.com/a/24103596/3946520
您可以在此处检查setCookie(),getCookie(),eraseCookie()的良好实现: https ://stackoverflow.com/a/24103596/3946520
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.