【发布时间】:2013-12-10 17:43:29
【问题描述】:
我创建了一个网站,该网站通过创建一个带有 +1 计数器的 cookie 来计算用户访问的次数。每五次访问后,它会要求用户注册。用户注册后,它会删除 cookie 并将其替换为注册信息(这是用于学校的,否则我永远不会这样做)。创建新 cookie 后,它会重定向到显示来自 cookie 的信息的新页面。然后,如果用户再次访问该站点,它应该在计数器开始之前重定向,使用与第一次重定向相同的标准。那是行不通的。无论如何,它都会创建计数器 cookie 而不会重定向。
我使用的代码是:
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
/////// Variable "name" is what gives the cookie its name. ///////
var name = "cookie";
function redirect() {
var x = document.forms.reg.first.value;
var y = document.forms.reg.last.value;
if (document.cookie == "Name: " + x + " Email: " + y) {
window.location="registered.html";
}
else {
setCookie();
}
}
/////// This function will set the cookie if no cookie exists. ///////
//////// Then it will add the value of 1 to the cookie name. ////////
function setCookie() {
if (document.cookie) {
i = document.cookie.indexOf(name);
}
else {
i = -1;
}
if (i == -1) {
document.cookie = name+ "=1; max-age=" +2592000;
}
else {
var start = (document.cookie.indexOf("=", i) + 1);
var end = document.cookie.indexOf(";", i);
if (end == -1) {
end = document.cookie.length;
}
var count = eval(document.cookie.substring(start, end)) + 1;
document.cookie = name+ "=" +count+ "; max-age=" + 2592000;
var popup = count % 5;
if (popup == 0) {
alert("Please Register");
}
else {
return
}
}
}
function formCheck() {
var x = document.forms.reg.first.value
var y = document.forms.reg.last.value
if (x =="") {
alert("Something");
return false;
}
if (y =="") {
alert("Something Else");
return false;
}
else {
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
document.cookie = "Name: " + x + " Email: " + y;
alert(document.cookie);
}
if (document.cookie == "Name: " + x + " Email: " + y){
window.location.replace("registered.html");
return false;
}
}
</script>
</head>
<body onload="redirect();">
<form name="reg" onSubmit="return(formCheck());">
Type your first name: <input type="text" name="first">
<br>
Type your last name: <input type="text" name="last">
<input type="submit">
</form>
</body>
</html>
</html>
任何帮助将不胜感激。从我问的最后一个问题开始,我已经走了很长一段路,几乎为自己感到自豪,但这让我很生气。我花了将近 20 个小时才走到这一步,而这是我最不需要的。
谢谢。
更新!
我能够使用重定向()的这项工作来使其工作
function redirect() {
if (document.cookie.length > 15) {
window.location.replace("registered.html");
}
else {
setCookie();
}
}
【问题讨论】:
-
因此,从我能够收集到的原因来看,重定向无法在访问中起作用,是因为它依赖于具有 x,y 值的 cookie,而这些值不再存在。那么,如果它们不再具有 document.form...." 的值,那么如果存在新的 cookie,那么另一种在访问时重定向的方法是什么?
-
您在registered.html上的代码是什么?
-
只是一个绑定到 body onload 的函数,它写出 cookie 的值。
标签: javascript redirect cookies