JavaScript Cookies

本文介绍如何使用JavaScript创建、读取及管理cookies。通过实例演示了如何根据用户输入创建cookie,并在用户再次访问时显示欢迎信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

cookie 用来识别用户。

http://www.w3school.com.cn/js/js_cookies.asp

实例

创建一个欢迎 cookie
利用用户在提示框中输入的数据创建一个 JavaScript Cookie,当该用户再次访问该页面时,根据 cookie 中的信息发出欢迎信息。

什么是cookie?

cookie 是存储于访问者的计算机中的变量。每当同一台计算机通过浏览器请求某个页面时,就会发送这个 cookie。你可以使用 JavaScript 来创建和取回 cookie 的值。

有关cookie的例子:

名字 cookie
当访问者首次访问页面时,他或她也许会填写他/她们的名字。名字会存储于 cookie 中。当访问者再次访问网站时,他们会收到类似 "Welcome John Doe!" 的欢迎词。而名字则是从 cookie 中取回的。
密码 cookie
当访问者首次访问页面时,他或她也许会填写他/她们的密码。密码也可被存储于 cookie 中。当他们再次访问网站时,密码就会从 cookie 中取回。
日期 cookie
当访问者首次访问你的网站时,当前的日期可存储于 cookie 中。当他们再次访问网站时,他们会收到类似这样的一条消息:"Your last visit was on Tuesday August 11, 2005!"。日期也是从 cookie 中取回的。

创建和存储 cookie

在这个例子中我们要创建一个存储访问者名字的 cookie。当访问者首次访问网站时,他们会被要求填写姓名。名字会存储于 cookie 中。当访问者再次访问网站时,他们就会收到欢迎词。

首先,我们会创建一个可在 cookie 变量中存储访问者姓名的函数:

function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}

上面这个函数中的参数存有 cookie 的名称、值以及过期天数。

在上面的函数中,我们首先将天数转换为有效的日期,然后,我们将 cookie 名称、值及其过期日期存入 document.cookie 对象。

之后,我们要创建另一个函数来检查是否已设置 cookie:

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return (document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}

上面的函数首先会检查 document.cookie 对象中是否存有 cookie。假如 document.cookie 对象存有某些 cookie,那么会继续检查我们指定的 cookie 是否已储存。如果找到了我们要的 cookie,就返回值,否则返回空字符串。

最后,我们要创建一个函数,这个函数的作用是:如果 cookie 已设置,则显示欢迎词,否则显示提示框来要求用户输入名字。

function checkCookie()
{
username=getCookie('username')
if (username!=null && username!="")
  {alert('Welcome again '+username+'!')}
else 
  {
  username=prompt('Please enter your name:',"")
  if (username!=null && username!="")
    {
    setCookie('username',username,365)
    }
  }
}

这是所有的代码:

<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return (document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}

function checkCookie()
{
username=getCookie('username')
if (username!=null && username!="")
  {alert('Welcome again '+username+'!')}
else 
  {
  username=prompt('Please enter your name:',"")
  if (username!=null && username!="")
    {
    setCookie('username',username,365)
    }
  }
}
</script>
</head>

<body onLoad="checkCookie()">
</body>
</html>
以下源码的用户和密码分别是:<!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" xml:lang="zh-CN" lang="zh-CN"> <head> <meta HTTP-EQUIV="Pragma" CONTENT="no-cache"> <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=GBK"> <title>安邦系统平台入口-登录验证</title> <style> *{margin:0px;padding:0px;} html,body{margin:0px; padding:0px;height:100%;width:100%;border:0px;} body{background:#6c6c6c;height:100%;width:100%;overflow:hidden;} .LoginDIV{width:700px;margin:0px auto;;padding:0px;overflow:hidden;} .FootDIV {width:700px;margin:0px auto;;padding:0px;overflow:hidden;text-align:center;} .TextInput{padding:3px 0px 3px 5px;width:100px;border-left:solid 1px #444444;border-top:solid 1px #444444;border-right:solid 1px #ffffff;;border-bottom:solid 1px #ffffff;font-size:13px;text-align:center;} </style> <script type="text/javascript" src="/js/jquery-1.8.3.min.js"></script> <script language='JavaScript'> function getObjByID(Id){if('object'==typeof(Id))return Id;else if('string'==typeof(Id))return document.getElementById(Id);else return null;} function SetCookie(inc_Name,INC_Value,INC_Hours) {   var TheEXP = new Date();   TheEXP.setTime(TheEXP.getTime() + 60*60*1000*INC_Hours);   document.cookie= inc_Name + "=" + INC_Value + ";expires="+ TheEXP.toGMTString(); } function GetCookie(inc_Name) {   var cookieString = new String(document.cookie);   var cookieHeader = inc_Name + "=";   var beginPosition = cookieString.indexOf(cookieHeader);   if (beginPosition != -1) { cookieString=cookieString.substring(beginPosition + cookieHeader.length); beginPosition=cookieString.indexOf(";") if (beginPosition != -1){cookieString=cookieString.substring(0,beginPosition);} return cookieString; }   else {return "";} } function GetAllCookie() { var CookieUserName=GetCookie('CKUserName'); var CookieUserPass=GetCookie('CKUserPass'); var CookieKeepMyInfo=GetCookie('CKKeepMyInfo'); document.getElementById('UserName').value=CookieUserName; document.getElementById('UserPass').value=CookieUserPass; if (CookieKeepMyInfo.replace(/\s*/,'')=='1') {document.getElementById('KeepMyInfo').value==1;} else {document.getElementById('KeepMyInfo').value==0;} } function CheckForm(inc_form) { var FOBJ=document.getElementById(inc_form); var UserName=FOBJ.UserName.value.replace(/\s*/g,''); var UserPass=FOBJ.UserPass.value.replace(/\s*/g,''); if (UserName==''){alert('请输入帐号');FOBJ.UserName.value='';FOBJ.UserName.focus();return false;} if (UserPass==''){alert('请输入密码');FOBJ.UserPass.value='';FOBJ.UserPass.focus();return false;} if (UserPass==''){alert('请输入密码');FOBJ.UserPass.value='';FOBJ.UserPass.focus();return false;} if (document.getElementById('KeepMyInfo').value==1) { SetCookie("CKUserName",UserName,48); SetCookie("CKUserPass",UserPass,48); SetCookie("CKKeepMyInfo",1,48); } else { SetCookie("CKUserName","",48); SetCookie("CKUserPass","",48); SetCookie("CKKeepMyInfo",0,48); } return true; } function CheckKeydown(inc_event,inc_NextOBJ,inc_FS) { if (inc_event.keyCode==13) { if (inc_FS==0) {document.getElementById(inc_NextOBJ).focus();} else { if(CheckForm(inc_NextOBJ)){document.getElementById(inc_NextOBJ).submit();} } } } function resizeWindow() { var BodyHeight=0; var TopDIVHeight=0; var LoginDIVHeight=0; var IMGLaoYingHeight=0; var IMGLaoYingWidth=0; BodyHeight=$("body").height(); LoginDIVHeight=$("#LoginDIV").height(); IMGLaoYingHeight=$("#IMGLaoYing").height(); TopDIVHeight=BodyHeight-LoginDIVHeight; var IMGMarginTop= (TopDIVHeight-IMGLaoYingHeight)/2.5 + 'px'; $("#TopDIV").height(TopDIVHeight); $("#IMGLaoYing").css("margin-top",IMGMarginTop); } $(document).ready(function(){resizeWindow();}); $(window).resize(function() {resizeWindow();}); </script> </head> <body onload="GetAllCookie();document.getElementById('UserName').focus();"> <div id="TopDIV" style="overflow:hidden;text-align:center;background:#000000;margin:0px auto;width:100%;background:#000000;height:70%"> <img id='IMGLaoYing' src="/images/laoying.png" style="height:55%;max-width:650px;"> </div> <div id="LoginDIV" style="overflow:hidden;text-align:center;background:#000000;margin:0px auto;width:100%;background:#c07814;height:200px"> <div style="overflow:hidden;height:50px;"> </div> <div style="overflow:hidden;margin:0px auto;width:500px;text-align:center;border:solid 0px #000000"> <form method='post' id='LogForm' name='LogForm' action='CheckPWD.php' style='margin:0px;padding:0px;overflow:hidden;'> <div style="overflow:hidden;float:left;margin-left:5px;"></div> <div style="overflow:hidden;float:left;font-size:13px;padding-top:3px;color:#222222;font-weight:bold;font-family:'Microsoft YaHei' ! important;">用  户:</div> <div style="overflow:hidden;float:left;margin-left:5px;"><Input Type="Text" class="TextInput" name="UserName" id="UserName" value="" maxlength="30" onkeydown="CheckKeydown(event,'UserPass',0);"></div> <div style="overflow:hidden;float:left;width:60px;"> </div> <div style="overflow:hidden;float:left;font-size:13px;padding-top:3px;color:#222222;font-weight:bold;font-family:'Microsoft YaHei' ! important;">密  码:</div> <div style="overflow:hidden;float:left;margin-left:5px;"><Input Type="password" class="TextInput" name="UserPass" id="UserPass" value="" maxlength="30" onkeydown="CheckKeydown(event,'LogForm',1);"></div> <div style="overflow:hidden;float:left;width:55px;"> </div> <div style="overflow:hidden;float:left;"> <Input Type="button" value=" 确 认 " onclick="if(CheckForm('LogForm')){LogForm.submit();}" style="width:80px;height:25px;background:#900a12;border:solid 0px #ffffff;font-size:13px;color:#ffffff;font-weight:bold;font-family:'Microsoft YaHei' ! important;"> <input type="hidden" id="KeepMyInfo" name="KeepMyInfo" value="1"> </div> </form> </div> <div style="clear:both;overflow:hidden;height:50px;"></div> <div style="overflow:hidden;text-align:center;font-size:12px;color:#333333">安邦咨询(ANBOUND)内部管理系统,&copy 2025</div> </div> </body> </html>
最新发布
05-28
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function testTion(){ var d =new Date(); var year=d.getFullYear(); var month=d.getMonth()+1; var day=d.getDate(); var hours=d.getHours(); var minutes=d.getMinutes(); var seconds=d.getSeconds(); var wd=d.getDay(); var wk=""; switch(wd){ case 1: wk="星期一"; break; case 2: wk="星期二"; break; case 3: wk="星期三"; break; case 4: wk="星期四"; break; case 5: wk="星期五"; break; case 6: wk="星期六"; break; default: wk="星期天"; } var result="今天是"+year+"年" +month+"月"+day+"&nbsp:"+hours+"时"+minutes+"分"+seconds+"秒&nbsp:"+wk; document.getElementById("d1").innerHTML=result; SetTimeout("testTime()",1000); } var testTime1=5; function test2(){ var b1=document.getElementById("b1"); if(testTime1<1){ location.href="http:/www.baidu.com"; }else{ b1.innerHTML=testTime1; testTime1--; setTimeout("test2()",1000); } } var tiem2=5; function daojishi(){ var btn=document.getElementById("btn1"); if(btn.value!="【我同意o】"){ if(tiem2<1){ btn.value="【我同意o】"; btn.disabled=false; }else{ btn.disabled="disabled"; btn.value="【我同意"+tiem2+"】"; tiem2--; SetTimeout("daojishi()",1000); } }else if(btn.value=="【我同意o】"){ location.href="http://www.baidu.com"; } } </script> </head> <body onload="testTime()"> <div id="d1"></div> <span>注册成功!系统将会在<b id="b1">5</b>秒内自动跳转!</span><br /> <input type="button" value="【我同意】" onclick="daojishiO()" id="btn1" /> </body> </html>检查代码
03-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值