zoukankan      html  css  js  c++  java
  • cookie学习

    cookie是储存于访问者的计算机中的变量,每当同一台计算机通过浏览器请求某个页面时,就会发送这个cookie,可以使用javascript来创建和取回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对象。

    escape()是对字符串进行编码,这样就可以在所有计算机上读取该字符串。

    检查是否已设置cookie:

    function getCookie(c_name){

     if(document.cookie.length>0){

       c_start=document.cookid.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))//substring()提取字符串中介于两个指定小标之间的字符。

      }

     }

    return ""

    }//首先检查document.cookie对象中是否存有cookie。加入有,那么继续检查我们制定的cookie是否储存。如果找到了我们要的cookie,则返回值,否则返回空字符串。

    indexOf(a,b)是检索字符串a在字符串中首次出现的位置,b指定开始检索的位置,在0-SringObject.length-1这个范围内。该方法对大小写敏感,没有找到返回-1。

    创建函数,作用是:如果cookid已设置,则显示欢迎词,否则显示提示框要求用户输入名字。

    function checkCookie(){

    username=getCookie('username')

    if(username!=null&&username!=""){

      alert("welcome again"+username+"!")

    }

      else{

         username=prompt('please enter your name:',"")//prompt(text,defaultText)用于显示可提示用户进行输入的对话框,text是对话框中显示的纯文本,后面为默认的输入文本。

         if(username!=null&&username!=""){

           setCookie('username',usename,365)

       }

     }

    }

  • 相关阅读:
    ctrl+shift+k取消
    ERROR 1872
    swap
    mysql主从跳过错误
    undo
    gtid
    falcon监控指标
    连接数
    datetime与timestamp相互转换
    截取文件内容
  • 原文地址:https://www.cnblogs.com/lionisnotkitty/p/5992108.html
Copyright © 2011-2022 走看看