服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

javascript实例教程(5) 在一个表单中设置和检查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文件并点击按钮你就回直接连到文档去。

扫描关注微信公众号