在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>

JS创建和存储 cookie的一些方法的更多相关文章

  1. 创建和存储 cookie

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

  2. JS创建类和对象(好多方法哟!)

    http://www.cnblogs.com/tiwlin/archive/2009/08/06/1540161.html 这是别人写的~~~我借来看看 JavaScript 创建类/对象的几种方式 ...

  3. js创建和获取cookie

    创建cookie document.cookie='like=1'; //创建 cookie键名和值 var str = document.cookie; 获取cookie 读取cookiefunct ...

  4. js 判断js函数、变量是否存在 JS保存和删除cookie操作,判断cookie是否存在的方法

    //是否存在指定函数 function isExitsFunction(funcName) {    try {        if (typeof(eval(funcName)) == " ...

  5. [JS]笔记15之客户端存储cookie

    -->本地存储发展情况 -->什么是cookie -->cookie优缺点 -->cookie的设置.读取.删除 -->cookie应用 本地存储发展情况 一.什么是co ...

  6. 易懂 易上手的cookie 最简单明了 js中cookie的使用方法及教程

    今天项目中需要用到cookie 看到我的cookie不行了 大喊一声我曹 怎么可以这样 我就疯狂的在网上找 找啊 找 但是我感觉都太官方了   废话不说 看栗子 1.引入jQuery与jQuery.C ...

  7. js动态创建及移除div的方法

    本文实例讲述了js动态创建及移除div的方法.分享给大家供大家参考.具体实现方法如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ...

  8. mvc存储Cookie和读取Cookie方法

    mvc存储Cookie和读取Cookie方法: //存储 HttpCookie cookie = new HttpCookie("User"); System.Text.Encod ...

  9. JS 无法清除Cookie的解决方法

    JS 无法清除Cookie的解决方法   项目中使用sdmenu.js时,需要在登录时清除Cookie,而sdmenu默认是会保存Cookie的 下面是sdmenu.js保存Cookie的方法 doc ...

随机推荐

  1. 多线程编程9认识等待函数WaitForSingleObject

    一下子跳到等待函数 WaitForSingleObject, 是因为下面的 Mutex.Semaphore.Event.WaitableTimer 等同步手段都要使用这个函数; 不过等待函数可不止 W ...

  2. 单层感知机_线性神经网络_BP神经网络

    单层感知机 单层感知机基础总结很详细的博客 关于单层感知机的视频 最终y=t,说明经过训练预测值和真实值一致.下面图是sign函数 根据感知机规则实现的上述题目的代码 import numpy as ...

  3. (转)java源程序加密解决方案(基于Classloader解密)

    转:http://cjnetwork.iteye.com/blog/851544 源程序加密解决方案 1. 概述: Java源程序的加密,有如下两种: 1使用混淆器对源码进行混淆,降低反编译工具的作用 ...

  4. 如何用excel统计调查问卷

    如何用excel统计调查问卷 有些人可能经常要对调查问卷进行统计,使用手写的方法(就是在纸上写正字的方法)虽然很方便,不过不方便在一定条件下进行统计,如在男士的条件下,使用诺基亚的手机有多少人.而用e ...

  5. USACO 2008 November Gold Cheering up the Cows /// MST oj24381

    题目大意: 输入n,p:n个点,p条路 接下来n行输入c[]:在各个点需要花费的时间 接下来p行输入u,v,w:u点到v点的路需要花费时间w 求经过所有点且最后回到起点的最少花费时间 https:// ...

  6. Startup里面的一些用法

    using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; usi ...

  7. cocos2dx触摸响应

      Layer其实继承了触控的接口. 所以只需要重写一些函数即可.   在helloword类中重写:     virtual bool init();     /** Callback functi ...

  8. SpringCloud学习笔记《---03 Ribbon---》基础篇

  9. Miler-Rabbin素数判定

    前言 素数判定? 小学生都可以打的出来! 直接暴力O(n)O(\sqrt n)O(n​)-- 然后就会发现,慢死了-- 于是我们想到了筛法,比如前几天说到的詹欧筛法. 但是线性的时间和空间成了硬伤-- ...

  10. 今天给各位介绍Linux touch命令详述

    触摸命令 touch命令有两个功能:一个是将现有文件的时间戳更新为系统的当前时间(默认模式),它们的数据将保持不变;第二个是创建一个新的空文件. 语法 触摸(可选) 最常见的用法:touch file ...