您的位置:首页 > Web前端 > JavaScript

JS创建和存储 cookie一些方法总结

2015-11-27 17:18 761 查看
在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 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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: