【发布时间】:2020-11-03 00:40:17
【问题描述】:
我在页面上有一个嵌入式表单。当页面加载时,它需要检查用户是否被 cookie。如果用户被 cookie,提醒他们。如果没有,请允许此人提交表单,然后对其进行 cookie。使用下面的代码,在页面加载时,用户会被 cookie 记录下来,并且总是看起来像返回用户,尽管只在提交时调用了 cookie 函数。
<body onLoad="checkCookieExists()">
<h1>Cookie test</h1>
<p>When the form loads, it will tell you if you've been here before based on the cookie.</p>
<form id="myForm" action="/">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
<script>
function checkCookieExists() {
if (document.cookie.indexOf('front-row=submitted')== -1 ) {
// New user
alert("this is your first time");
console.log("existcookienew");
}
else {
// They've been here before.
alert("hello again");
}
}
document.getElementById("myForm").addEventListener("submit", checkCookie());
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 + ";path=/";
}
function checkCookie() {
setCookie("front-row", "submitted", 30);
}
</script>
'''
【问题讨论】:
标签: javascript html forms cookies