写入cookie
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
function doWrite(){
var username=encodeURIComponent(document.getElementById("username").value);
var password=encodeURIComponent(document.getElementById("password").value);
console.log(username);
var today=new Date();
var expiresDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()+7);
var str1="username="+username+";expires="+expiresDate.toGMTString();
document.cookie=str1;
var str2="password="+password;
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;
var array=str.split("; ");
for(var i=0;i<array.length;i++){
var array2=array[i].split("=");
console.log(array2[0]+":"+decodeURIComponent(array2[1]));
}
}
function doRead(key){
var str=document.cookie;
var index=str.indexOf(key+"=");
var start=index+key.length+1;
var end=str.indexOf(";",start);
if(end==-1){
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>