我正在努力了解Cookie在JavaScript中的运作方式。
以下是我要做的事情: 写出一个名为" Library"并设置21天的到期日期和 使用警报让用户知道cookie已创建
将用户重定向到另一个页面" blah.html"如果没有错误发生(用户名或密码在表单上留空)并发布消息,以显示"欢迎," +用户名"!";。如果发生错误,请重定向到blah2.html并提醒用户该错误。任何帮助将不胜感激!提前谢谢!
我的Cookie代码:
function writeCookie() {
if (document.myForm.username.value == "") {
alert("You did not enter a user name!");
window.location.href. = "home.html";
} else if (document.myForm.pwd.value == "") {
alert("You did not enter a password!");
window.location.href = "home.html";
} else
cookieValue = escape(document.myForm.username.value) + ";";
document.cookie = "name=" + cookieValue;
alert("Setting Cookies: " + "name=" + cookieValue);
window.location.href = "private.html";
}
function getCookie() {
var userWelcome = document.cookie;
}
我的HTML代码:
<p> Welcome to the Login Screen. To continue, please enter your username and password</p>
<form name="myForm">
<fieldset>
<legend><b>User Information</b></legend><br>
<label for="username">User Name:</label>
<input name="username" size="20" maxlength="20" type="text">
<label for="pwd">Password:</label>
<input name="pwd" size="25" maxlength="25" type="password">
<br>
<br>
<center>
<input type="Submit" value="Login" id="login" onclick="createCookie
();"> <input value="Reset" type="reset"></center>
</fieldset>
</form>
答案 0 :(得分:0)
所以我移动了一些东西并清理了错误。
此行有错误:window.location.href.
它应该是:window.location.href
<script>
function writeCookie(){
try{
if(document.myForm.username.value == ""){
alert("You did not enter a user name!");
return false;
} else if(document.myForm.pwd.value == ""){
alert("You did not enter a password!");
return false;
} else {
cookieValue = escape(document.myForm.username.value) +";";
document.cookie = "name=" + cookieValue;
alert("Setting Cookies: " + "name=" + cookieValue);
window.location.href = "private.html";
}
} catch(e){alert(e); return false;}
}
function getCookie(){
var userWelcome = document.cookie;
}
</script>
<p> Welcome to the Login Screen. To continue, please enter your username and password</p>
<form name="myForm" onsubmit="return writeCookie()" action="post">
<fieldset>
<legend><b>User Information</b></legend><br>
<label for="username">User Name:</label>
<input name="username" size="20" maxlength="20" type="text">
<label for="pwd">Password:</label>
<input name="pwd" size="25" maxlength="25" type="password">
<br>
<br>
我使用了表单的onsubmit操作,如果用户没有输入用户名和密码而不是重定向,它将返回false。 (我假设你将它重定向到同一页面)。目前,您的代码也在我删除错误后设置了cookie值。
这是一个显示正常工作的JSFiddle。
要检索cookie,只需执行
var cookie = document.cookie;
var name = cookie.split('=')[1];