javascript对cookie的常用操作
<!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添、删、显、修改</title>
<style>
body { line-height:22px; font-size:12px;}
#cookieWrite {border:2px solid #ccc;background:#ebebeb;padding:10px;}
</style>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
function getCookie(cookieName) {
var cookieString = document.cookie;
var start = cookieString.indexOf(cookieName + '=');
// 加上等号的原因是避免在某些 Cookie 的值里有
// 与 cookieName 一样的字符串。
if (start == -1) // 找不到
return null;
start += cookieName.length + 1;
var end = cookieString.indexOf(';', start);
if (end == -1) return unescape(cookieString.substring(start));
return unescape(cookieString.substring(start, end));
};
//显示单条Cookie
function aloneCookie() {
var cooname = $("alone").value
var cookie = getCookie(cooname);
if (cooname != "") {
$("cookieWrite").innerHTML = "您查询的<b> " + cooname + " </b>的cookie的值 = " + cookie;
}else{
alert("请输入Cookie名称!")
}
};
//显示所有Cookie
function allCookie() {
var allCookie = document.cookie;
if (allCookie != ""){
$("cookieWrite").innerHTML = allCookie;
}else{
$("cookieWrite").innerHTML = "非常抱歉!暂时没有Cookie显示。";
};
};
//添加一条Cookie纪录
function addCookie(name,cookievalue,time) {
var name = $("addname").value;
var cookievalue = $("addvalue").value;
var time = $("addtime").value;
if (name != "" && cookievalue != "" && time != "") {
if (isNaN(time) == false){ //判断输入的值是否为数字
var expires = new Date();
expires.setTime(expires.getTime() + time * 1000);
document.cookie = name + '=' + escape(cookievalue) + ';expires=' + expires.toGMTString();
alert("恭喜您!添加成功!")
}else{
alert("\"Cookie存储时间\" 请填写数字!")
};
}else{
alert("请确保以上3个输入框都有值!")
};
}
//删除一条Cookie纪录
function clearCookie(name) {
var name = $("clearCookie").value;
var cookievalue = getCookie(name);//为了不更改当前Cookie的值才加的这句
if (name != ""){
var expires = new Date();
expires.setTime(expires.getTime() -1);
document.cookie = name + '=' + escape(cookievalue) + ';expires=' + expires.toGMTString();
alert("恭喜您!删除成功!")
}else{
alert("请输入Cookie名称!")
};
}
</script>
</head>
<body>
<br /><br /><br />
Cookie名称:<input type="text" id="addname" /> Cookie值:<input type="text" id="addvalue" /> Cookie存储时间:<input type="text" id="addtime" />秒
<input type="button" onclick="addCookie()" value="添加一条Cookie" /><br /><br />
<input type="text" id="alone" />
<input type="button" onclick="aloneCookie()" value="显示这条cookie的值" /><br /><br />
<input type="text" id="clearCookie" />
<input type="button" onclick="clearCookie()" value="清除这条cookie" /><br /><br />
<input type="button" onclick="allCookie()" value="显示所有cookie" />
<br /><br /><br /><br />
<div id="cookieWrite">这里显示结果</div>
</body>
</html>