我正在尝试在 Javascript 中使用 cookie,但它不起作用。我不明白这个问题。下面给出的是我的代码。请帮忙。
索引.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org
/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>WelcomePage</title>
<script type="text/javascript">
function setCookie()
{
var name= document.getElementById("username").value;
var expires="";
if(name=="")
{
alert("Please Enter A Valid Name");
return false;
}
else
{
var date = new Date();
date.setTime(date.getTime()+ (2*24*60*60*1000));
expires = "; expires= "+ date.toGMTString();
var cookieExp = "name="+name+expires+"; path=/";
alert(cookieExp);
document.cookie(cookieExp);
form.submit();
}
}
</script>
</head>
<body bgcolor="#C0C0C0">
<hr size="1"width="1200">
<form method= "post" action="Second.html">
<table align="center">
<tr>
<td align="center">Enter Name: </td>
<td><input type="text" size="10" id="username" name= "user"></td>
<td align="center"><input type="submit"value="submit" onclick="return setCookie();">
</td>
</tr>
</table>
</form>
<hr size="1"width="1200">
</body>
</html>
这是我试图检索 cookie 但警报框返回未定义值的第二页。
第二个.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org
/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>2ndPage</title>
<script type="text/javascript">
function getCookie()
{
var allCookies = document.cookie;
alert("All Cookies: "+allCookies);
cookieArray = allCookies.split(';');
for(var i=0;i<cookieArray.length;i++)
{
name = cookieArray[i].split("=")[0];
value = cookieArray[i].split("=")[1];
alert("Key is: "+name+" Value is: "+value);
}
}
</script>
</head>
<body bgcolor="#C0C0C0" onload="getCookie();">
<hr size="1"width="1200">
<br><br>
<hr size="1"width="1200">
</body>
</html>