cookie基础
什么是cookie
页面用来保存信息
比如:自动登录、记住用户名
cookie的特性
同一个网站中所有页面共享一套cookie
数量、大小有限
过期时间
JS中使用cookie
document.cookie
使用cookie——1
cookie的使用
设置cookie
格式:名字=值
不会覆盖
过期时间:erpires = 时间
日期对象的使用
var oDate = new Date();
oDate.setDate(oDate.getDate() + 14);
document.cookie = 'user = blue; expires = '+ oDate;
alert(document.cookie);
封装函数
function setCookie(name, value, iDay){
var oDate = new Date();
oDate.setDate(oDate.getDate() + iDay);
document.cookie = name +' ='+ value +'; expires = '+ oDate;
}
setCookie('userName','blue',365);
setCookie('password','123456',14);
读取cookie
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
</style>
<script type="text/javascript">
function setCookie(name, value, iDay){
var oDate = new Date();
oDate.setDate(oDate.getDate() + iDay);
document.cookie = name +' ='+ value +'; expires = '+ oDate;
}
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 '';
}
alert(getCookie('userName'));
</script>
</head>
<body>
</body>
</html>
字符串分割
删除cookie
已经过期
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
</style>
<script type="text/javascript">
function setCookie(name, value, iDay){
var oDate = new Date();
oDate.setDate(oDate.getDate() + iDay);
document.cookie = name +' ='+ value +'; expires = '+ oDate;
}
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 '';
}
function removeCookie(name){
setCookie(name, 1, -1);
}
removeCookie('userName');
alert(document.cookie);
</script>
</head>
<body>
</body>
</html>
使用cookie——2
cookie的使用
例子
用cookie记录上次登录的用户名
提交时——记录用户名
window.onload——读取用户名
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
function setCookie(name, value, iDay){
var oDate = new Date();
oDate.setDate(oDate.getDate() + iDay);
document.cookie = name +' ='+ value +'; expires = '+ oDate;
}
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 '';
}
function removeCookie(name){
setCookie(name, 1, -1);
}
window.onload = function (){
var oForm = document.getElementById('form1');
var oUser = document.getElementsByName('user')[0];
oForm.onsubmit = function(){
setCookie('user',oUser.value,14);
}
oUser.value = getCookie('user');
}
</script>
</head>
<body>
<form id="form1" action="http://www.baidu.com/">
用户名:<input type="text" name = "user" /><br>
密码:<input type="password" name = 'pass' /><br>
<input type="submit" value="登录" />
</form>
</body>
</html>