cookie的应用

cookie的基础:

同一网站,其域名一样

cookie的特点:

同一个网站共享一套cookie;

数量大小有限制;

有过期时间;

 

js使用cookie:

  document.cookie

cookie的封装

 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>cookie</title>
</head>
<body>
	
</body>
<script>
	// 封装设置cookie的方法
	function setCookie(name,value,iDay){
		var oDate = new Date();
		oDate.setDate(oDate.getDate()+iDay);
		document.cookie=name+'='+value+';expires='+oDate;
	}

	// 读取cookie中的某个数据
	function getCookie(name){
       var arr = document.cookie.split('; ');//分割
       for (var i = 0; i < arr.length; i++) {
       		var arr2 = arr[i].split('=');
       		if (arr2[0] == name) {
       			return arr2[1];
       		}
       
       return '';
	}

	// 移除cookie中的数据
	function removeCookie(name){
		setCookie(name,1,-1);//-1表示已经过期
	}
	// setCookie('username','lxs',2);
	// setCookie('psw','1122',5);
	alert(document.cookie);
	removeCookie('passwords');
</script>
</html>

  cookie的demo案例:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script>
		function setCookie(name,value,iDay){
		var oDate = new Date();
		oDate.setDate(oDate.getDate()+iDay);
		document.cookie=name+'='+value+';expires='+oDate;
	}

	// 读取cookie中的某个数据
	function getCookie(name){
       var arr = document.cookie.split('; ');//分割
       for (var i = 0; i < arr.length; i++) {
       		var arr2 = arr[i].split('=');
       		if (arr2[0] == name) {
       			return arr2[1];
       		}
       
       return '';
	}

	// 移除cookie中的数据
	function removeCookie(name){
		setCookie(name,1,-1);//-1表示已经过期
	}
		window.onload=function () {
			var form1 = document.getElementById('form1');
			var user = document.getElementsByName('user')[0];
			form1.onsubmit=function(){
					setCookie('user1',user.value,10);
					
			}
		}
	</script>
</head>
<body>
	<form id="form1" action="http://www.zhinengshe.com">
		user:<input type="text" name="user"><br>
		pwd: <input type="password" name="pass"><br>
		<input type="submit" value="login">
	</form>
</body>
</html>

  

posted on 2018-10-28 16:23  婧星  阅读(344)  评论(0编辑  收藏  举报

导航