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

用js操作cookie保存浏览记录

2013-01-17 15:21 447 查看
cookie 与 session 是中常用的信息存储方式。Cookie是在客户端开辟的一块可存储用户信息的地方;Session是在服务器内存中开辟的一块存储用户信息的地方.JavaScript是运行在客户端的脚本,因此一般是不能够设置Session的,因为Session是运行在服务器端的。

而cookie是运行在客户端的,所以可以用JS来设置cookie.

假设有这样一种情况,在某个用例流程中,由A页面跳至B页面,若在A页面中采用JS用变量temp保存了某一变量的值,在B页面的时候,同样需要使用JS
来引用temp的变量值,对于JS中的全局变量或者静态变量的生命周期是有限的,当发生页面跳转或者页面关闭的时候,这些变量的值会重新载入,即没有达到
保存的效果。解决这个问题的最好的方案是采用cookie来保存该变量的值,那么如何来设置和读取cookie呢?

首先需要稍微了解一下cookie的结构,简单地说:cookie是以键值对的形式保存的,即key=value的格式。各个cookie之间一般是以“;”分隔。

JS设置cookie:

假设在A页面中要保存变量username的值("jack")到cookie中,key值为name,则相应的JS代码为:

document.cookie="name="+username;

JS读取cookie:

假设cookie中存储的内容为:name=jack;password=123

则在B页面中获取变量username的值的JS代码如下:

var username=document.cookie.split(";")[0].split("=")[1];

//JS操作cookies方法!

//写cookies

function setCookie(name,value)
{
var Days =
30;
var exp =
new Date();
exp.setTime(exp.getTime() +
Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) +
";expires=" + exp.toGMTString();

var strsec =
getsec(time);
var exp =
new Date();
exp.setTime(exp.getTime() + strsec*1);
document.cookie = name + "="+ escape (value) +
";expires=" + exp.toGMTString();
}

//读取cookies
function getCookie(name)
{
var
arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");

if(arr=document.cookie.match(reg))

return (arr[2]);
else
return null;
}

//删除cookies
function delCookie(name)
{
var exp =
new Date();
exp.setTime(exp.getTime() - 1);
var
cval=getCookie(name);
if(cval!=null)
document.cookie= name +
"="+cval+";expires="+exp.toGMTString();
}
//使用示例
setCookie("name","hayden");
alert(getCookie("name"));

//如果需要设定自定义过期时间
//那么把上面的setCookie 函数换成下面两个函数就ok;

//程序代码
function setCookie(name,value,time)
{
var strsec =
getsec(time);
var exp =
new Date();
exp.setTime(exp.getTime() + strsec*1);
document.cookie = name + "="+ escape (value) +
";expires=" + exp.toGMTString();
}

function getsec(str)
{
alert(str);
var
str1=str.substring(1,str.length)*1;
var
str2=str.substring(0,1);
if (str2=="s")
{
return str1*1000;
}
else if (str2=="h")
{
return str1*60*60*1000;
}
else if (str2=="d")
{
return str1*24*60*60*1000;
}
}
//这是有设定过期时间的使用示例:
//s20是代表20秒
//h是指小时,如12小时则是:h12
//d是天数,30天则:d30

setCookie("name","hayden","s20");

-----------------------

说明:最近做了一个功能,记录用户浏览过的产品页面。我的思路是,客户每次进入产品页面,就自己调用JS把产品信息以json的形式保存到cookie里面。
浏览记录的显示是从cookie里读出来,然后解析成json,生成html元素。因为用户可能会同时打开好几个页面,这几个页面上可能都有浏览记录,为了使即使显示浏览记录,每秒中刷新一次。
要用到2个js文件,history.js,关键的聊天记录保存和读取代码。json.js,对json进行处理。
http://www.cnblogs.com/qinying/archive/2010/09/15/1826846.html
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.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;
}
}
示例程序

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