JS创建和存储 cookie的一些方法

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>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/112742.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 数据挖掘选择题_数据挖掘算法例题

    数据挖掘选择题_数据挖掘算法例题目录一、填空题二、计算题一、填空题❃随着信息技术的高速发展,数据库应用的规模、范围和深度不断扩大,网络环境成为主流等等。产生“数据丰富而信息贫乏”现象。❃“数据丰富而信息贫乏”现象导致大数据概念。❃数据(Data)、信息(Information)和知识(Knowledge)是广义数据表现的不同形式。❃大数据时代的数据挖掘技术需求分析的流派:数据论、方法论、环境论、特征论…

    2022年9月4日
    2
  • PLSQL详细使用教程及下载地址「建议收藏」

    PLSQL详细使用教程及下载地址「建议收藏」Oracle数据库连接必备,大公司玩转oracle数据库必备,虽然现在已经都用MYSQL替换了,但是不可否认这款软件的实力。中文版还具有语法加强、SQL和PL/SQL帮助、对象描述等功能特性。下载地址:http://kk04.cn/f-6339.html详细使用教程:http://kk04.cn/f-6342.html…

    2022年5月2日
    48
  • ios激活成功教程软件_qt.qpa.plugin:Could not

    ios激活成功教程软件_qt.qpa.plugin:Could not注意:一定要手动创建文件夹,在相应文件夹下进行操作,否则无法成功生成注册码激活成功教程步骤:1.安装qtp,一路默认下来,到要求输入License的界面2.拷贝mgn-mqt82.exe(下载)到C:\ProgramFiles\MercuryInteractive(自己手动创建)文件夹下3.自己手动创建C:\ProgramFiles\CommonFiles\Mercury

    2022年10月1日
    0
  • Linux Platform devices 平台设备驱动

    Linux Platform devices 平台设备驱动platform平台设备驱动是基于设备总线驱动模型的,它只不过是将device进一步封装成为platform_device,将device_driver进一步封装成为platform_device_driver,前面已经分析过设备总线驱动模型,关于device与device_driver的注册过程以及它们在sysfs文件系统中的层次关系就不在分析,本文重点分析platform平台

    2022年7月24日
    7
  • 使用joi来验证数据模型[通俗易懂]

    使用joi来验证数据模型[通俗易懂]我们用nodejs实现一些功能时,往往需要对用户输入的数据进行验证。然而,验证是一件麻烦的事情,很有可能你需要验证数据类型,长度,特定规则等等,在前端做表单验证时,我们常用的做法是使用正则,正则表达式

    2022年8月1日
    13
  • 初识不知曲中意,再听已是曲中人下一句是什么_调用action方法出错

    初识不知曲中意,再听已是曲中人下一句是什么_调用action方法出错动作类是多例的,每次动作访问,动作类都会实例化。所以是线程安全的。在每次动作执行前,核心控制器StrutsPrepareAndExecuteFilter都会创建一个ActionContext和ValueStack对象。且每次动作访问都会创建。这两个对象存储了整个动作访问期间用到的数据。并且把数据绑定到了线程局部变量(ThreadLocal)上了。所以是线程安全的。contextMap使用struts内置标签<s:debug>查看contextMap数据利用ActionCo.

    2022年9月9日
    1

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号