<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cookie读写demo</title>
<script>
var cookieName = "demo";
/** 创建cookie */
function createCookie(){
var username = document.getElementById("username").value;
var date= new Date(); // 定义时间
var days=30; // 保存天数
date.setTime(date.getTime()+(days*24*60*60*1000)); // 原有时间相加后获取有效期时间
//cookie由两部分组成name=value;有效期=值
document.cookie=cookieName+"="+username+";expires="+date.toGMTString();
}
/** 读取cookie */
function getCookie()//取cookies函数
{
var arr = document.cookie.match(new RegExp("(^| )"+cookieName+"=([^;]*)(;|$)"));
if(arr != null){
var username = arr[2];
document.getElementById("username").value = username;
}
}
</script>
</head>
<body>
<input type="text" id="username" name="username">
<input type="button" value="生成Cookie" οnclick="createCookie();">
<input type="button" value="读Cookie" οnclick="getCookie();"/>
</body>
</html>
Cookie读写demo
最新推荐文章于 2024-09-11 12:01:27 发布