>>>>> 创建和储存cookie

什么是cookie?

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

<html>
<head>
<script type="text/javascript">
//获取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 unescape(document.cookie.substring(c_start,c_end))
     } 
    }
    return ""
 }
//设置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
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,30)
    }
  }
}
</script>
</head>
<body onLoad="checkCookie()">
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容