在一个表单中设置和检查Cookies

Cookie是一小段由浏览器储存起来帮助识别用户身份的信息。在一个表单中设置和检查Cookies的实现需要两个文件来完成。第一个文件为cookie1.html,这个文件需要有一些机理(下面例子的一个按钮)来检查是否有一个Cookie存在,然后再重定向至表单网页或者文档下载网页。而第二个文件,即表单网页(cookie2.html),也是和重要的因为你将要在上面使用一点点JavaScript来设置Cookie,这个设置是在提交表单之前做的。下面给出这文件:

第一个文件(cookie1.html)

<html>

<head>

<script LANGUAGE=”JavaScript”>

<!–

function cookieRedirect(hasCookieURL, noCookieURL)

{

var currentCookie = document.cookie;

if (currentCookie.indexOf(“formcomplete=yes”) != -1) {

window.location = hasCookieURL;

} else {

window.location = noCookieURL;

}

}

// –>

</script>

</head>

<body>

<form NAME=”docdownload”>

<input TYPE=”BUTTON” VALUE=”Download document”

onClick=”cookieRedirect(‘doc.html’, ‘cookie2.html’)”>

</form>

</body>

</html>
第二个文件(cookie2.html ) <html>

<head>

<script LANGUAGE=”JavaScript”>

<!–

function sendForm(objForm)

{

cookieExpires = “Saturday, 01-Jan-03 00:00:00 GMT”;

document.cookie = “formcomplete=yes; path=/”;

// objForm.submit();

}

// –>

</script>

</head>

<body>

<form ACTION=”test.html” NAME=”info”>

<table>

<tr>

<td>First name</td>

<td><input TYPE=”TEXT” NAME=”firstname”></td>

</tr>

<td>Last name</td>

<td><input TYPE=”TEXT” NAME=”lastname”></td>

</tr>

<tr>

<td>Address</td>

<td><input TYPE=”TEXT” NAME=”address”></td>

</tr>

<tr>

<td>City</td>

<td><input TYPE=”TEXT” NAME=”city”></td>

</tr>

<tr>

<td>State</td>

<td><input TYPE=”TEXT” NAME=”state”></td>

</tr>

<tr>

<td>Zip</td>

<td><input TYPE=”TEXT” NAME=”zip”></td>

</tr>

</table>

<input TYPE=”BUTTON” VALUE=”Download document”

onClick=”sendForm(document.testform)”>

</form>

</body>

</html>

下面再给出需要用到的doc.html文件:

doc.html

<html>

<body>

<h3>This is the document</h3>

</body>

</html>

为了测试一下这个功能,你可以打开cookie1.html并点击中按钮,你将被带到表单网页。如果你回到cookie1.html文件并点击按钮你就回直接连到文档去。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部