zoukankan      html  css  js  c++  java
  • JS创建和存储 cookie的一些方法

    在js中cookie的操作与存储及清除cookie都与时间有关,我们只要把cookie过期时间进行有效的设置我们就可以控制它的存储了,下面我来给大家总结一下js中cookie的一些使用技巧

    创建和存储 cookie

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

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

     代码如下复制代码

    function Setcookie (name, value)

        //设置名称为name,值为value的Cookie
        var expdate = new Date();   //初始化时间
        expdate.setTime(expdate.getTime() + 30 * 60 * 1000);   //时间
        document.cookie = name+"="+value+";expires="+expdate.toGMTString()+";path=/";

       //即document.cookie= name+"="+value+";path=/";   时间可以不要,但路径(path)必须要填写,因为JS的默认路径是当前页,如果不填,此cookie只在当前页面生效!~
    }


    上面这个函数中的参数存有 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 unescape(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)
        }
      }
    }

         

    一个完整实例

     

     代码如下 复制代码

    <!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>无标题文档</title>
    <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 unescape(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>


    上面讲到了cookie的创建我们现在来看一个利用cookie保存浏览记录实例

    浏览记录的显示是从cookie里读出来,然后解析成json,生成html元素。因为用户可能会同时打开好几个页面,这几个页面上可能都有浏览记录,为了使即使显示浏览记录,每秒中刷新一次。
    要用到2个js文件,history.js,关键的聊天记录保存和读取代码。json.js,对json进行处理。

    history.js

     代码如下 复制代码

    var addHistory=function(num,id){
        stringCookie=getCookie('history');
        var stringHistory=""!=stringCookie?stringCookie:"{history:[]}";
        var json=new JSON(stringHistory);
        var e="{num:"+num+",id:"+id+"}";
        json['history'].push(e);//添加一个新的记录
        setCookie('history',json.toString(),30);
    }
    //显示历史记录
    var DisplayHistory=function(){
        var p_ele=document.getElementById('history');
         while (p_ele.firstChild) {
          p_ele.removeChild(p_ele.firstChild);
         }

        var historyJSON=getCookie('history');
        var json=new JSON(historyJSON);
        var displayNum=6;
        for(i=json['history'].length-1;i>0;i--){
            addLi(json['history'][i]['num'],json['history'][i]['id'],"history");
            displayNum--;
            if(displayNum==0){break;}
        }
    }
    //添加一个li元素
    var addLi=function(num,id,pid){
        var a=document.createElement('a');
        var href='product.action?pid='+id;
        a.setAttribute('href',href);
        var t=document.createTextNode(num);
        a.appendChild(t);
        var li=document.createElement('li');
        li.appendChild(a);
        document.getElementById(pid).appendChild(li);
    }
    //添加cookie
    var setCookie=function(c_name,value,expiredays)
    {
        var exdate=new Date()
        exdate.setDate(exdate.getDate()+expiredays)
        cookieVal=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
    //    alert(cookieVal);
        document.cookie=cookieVal;
    }
    //获取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
    //        document.write(document.cookie.substring(c_start,c_end)+"<br>");
            return unescape(document.cookie.substring(c_start,c_end))
            } 
          }
        return ""
    }

    json文件

     代码如下 复制代码

    json.js 
    var JSON = function(sJSON){
        this.objType = (typeof sJSON);
        this.self = [];
        (function(s,o){for(var i in o){o.hasOwnProperty(i)&&(s[i]=o[i],s.self[i]=o[i])};})(this,(this.objType=='string')?eval('0,'+sJSON):sJSON);
    }
    JSON.prototype = {
        toString:function(){
            return this.getString();
        },
        valueOf:function(){
            return this.getString();
        },
        getString:function(){
            var sA = [];
            (function(o){
                var oo = null;
                sA.push('{');
                for(var i in o){
                    if(o.hasOwnProperty(i) && i!='prototype'){
                        oo = o[i];
                        if(oo instanceof Array){
                            sA.push(i+':[');
                            for(var b in oo){
                                if(oo.hasOwnProperty(b) && b!='prototype'){
                                    sA.push(oo[b]+',');
                                    if(typeof oo[b]=='object') arguments.callee(oo[b]);
                                }
                            }
                            sA.push('],');
                            continue;
                        }else{
                            sA.push(i+':'+oo+',');
                        }
                        if(typeof oo=='object') arguments.callee(oo);
                    }
                }
                sA.push('},');
            })(this.self);
            return sA.slice(0).join('').replace(/[object object],/ig,'').replace(/,}/g,'}').replace(/,]/g,']').slice(0,-1);
        },
        push:function(sName,sValue){
            this.self[sName] = sValue;
            this[sName] = sValue;
        }
    }

    html文档

     代码如下 复制代码

    示例程序 
    <script type="text/javascript" src="../js/json.js"></script>
    <script type="text/javascript" src="../js/history.js"></script>
    <ul id="history">
    </ul>
    <script> 
    addHistory(15810782304,2);
    addHistory(64654665,2);
    addHistory(6843212,2);
    addHistory(84984432521,2);
    setInterval("DisplayHistory()",1000);
    </script>

  • 相关阅读:
    Linux定制化RPM包
    01-if条件语句之数字比较
    01-爬虫介绍
    Django的路由系统01-路由分发
    Nginx+tomcat+redis集群共享session实现负载均衡
    CAS单点登录原理
    红黑树
    B+树
    Mysql索引介绍
    B树(B-树)
  • 原文地址:https://www.cnblogs.com/lxwphp/p/15453793.html
Copyright © 2011-2022 走看看