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

本文详细讲解了JavaScript中如何进行cookie的读取和写入操作,包括具体的代码实现,是学习Cookie管理的第一课。
摘要由CSDN通过智能技术生成
写入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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值