javascript操作cookie范例

本文介绍了一种使用JavaScript来设置、读取及删除Cookie的方法。通过简单的表单输入,可以实现Cookie的有效期设置,并且能够展示当前存在的Cookie内容,同时提供了清除特定Cookie的功能。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
	<head>
//直接复制拷贝 运行可以看到效果
		<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
		<title>Cookie的使用方法</title>
		<script language="javascript" type="text/javascript">
//检查Cookie是否有效   
function setCookie() {

	if (!navigator.cookieEnabled) {

		alert('不Cookie项!');

	} else {

		var date = new Date();

		date.setTime(date.getTime() + 60000 * 10);

		document.cookie = 'userName=' + escape(document.form1.userName.value)
				+ ';expires=' + date.toGMTString() + ';path=/'
				+ ';domaim=zgdsc.cn' + ':secure';

	}

}

function showValue() {

	alert(unescape(document.cookie));

}

function clearValue() {

	var date = new Date();

	date.setTime(date.getTime() - 1);

	document.cookie = 'userName=' + escape(document.form1.userName.value)
			+ ';expires=' + date.toGMTString() + ';path=/' + ';domain=zgdsc.cn'
			+ ';secure';

}
</script>
	</head>
	<body>
		<form id="form1" name="form1" method="post" action="#">
			输入用户名:
			<input type="text" name="userName" />
			<input type="radio" name="cookieEnabled" value="radiobutton" onclick="setCookie()" />
			保存Cookie
			<label>
				<input type="button" name="Submit" value="显示" onclick="showValue()" />
			</label>
			<label>
				<input type="button" name="Submit2" value="清除"
					onclick="clearValue()" />
			</label>
		</form>
	</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值