Javascript第七章cookie的读取和写入源码第一课

版权声明:本文为博主原创文章,未经博主允许不得转载。如有问题,欢迎指正。 https://blog.csdn.net/qq_30225725/article/details/89325969

写入cookie

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script type="text/javascript">
		/**
		 * 查看Cookie:打开Chrome开发人员工具——Application——Storage——Cookies
		 */
		function doWrite(){
			// var username=document.getElementById("username").value;
			// var password=document.getElementById("password").value;
			var username=encodeURIComponent(document.getElementById("username").value); //编码
			var password=encodeURIComponent(document.getElementById("password").value);
			console.log(username); //不能使用encodeURI,其不会对分号进行编码
//取当前的日期
			var today=new Date();
			var expiresDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()+7); //保存7天
//toGMTString() 方法可根据格林威治时间 (GMT) 把 Date 对象转换为字符串,并返回结果。
			var str1="username="+username+";expires="+expiresDate.toGMTString();
			document.cookie=str1;

			var str2="password="+password;  //iloveyou  jmpwfzpv
			document.cookie=str2;

			var str3="age=23;expires="+expiresDate.toGMTString();
			document.cookie=str3;

			console.log("写入Cookie成功!");

		}
	</script>
</head>
<body>
	用户名:<input type="text" id="username"><br>
	密码:<input type="password" id="password"><br>
	<input type="button" value="写入Cookie" onclick="doWrite()">
</body>
</html>

读cookie

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script type="text/javascript">
		function doReadAll(){
			var str=document.cookie;
			// console.log(str);
			var array=str.split("; ");
			for(var i=0;i<array.length;i++){
				// console.log(array[i]);
				var array2=array[i].split("=");
				console.log(array2[0]+":"+decodeURIComponent(array2[1])); //解码
			}
		}

		//username=tom; password=abc; age=23
		function doRead(key){ //password
			//读取所有Cookie
			var str=document.cookie;
			//获取key出现的位置
			var index=str.indexOf(key+"=");
			//获取截取的起始位置 
			var start=index+key.length+1;
			//获取截取的结束位置
			var end=str.indexOf(";",start);
			//截取value
			if(end==-1){ //如果找不到分号,说明是最后一个cookie
				var value=str.substring(start);
			}else{
				var value=str.substring(start,end);
			}

			console.log(key+":"+value);
		}
	</script>
</head>
<body>
	<input type="button" value="读取所有Cookie" onclick="doReadAll()">
	<input type="button" value="读取Cookie中的password" onclick="doRead('password')">
	<input type="button" value="读取Cookie中的age" onclick="doRead('age')">
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_30225725/article/details/89325969
今日推荐