js操作cookie保存浏览记录的方法
本文实例讲述了js操作cookie保存浏览记录的方法。分享给大家供大家参考,具体如下:
说明:最近做了一个功能,记录用户浏览过的产品页面。我的思路是,客户每次进入产品页面,就自己调用JS把产品信息以json的形式保存到cookie里面。
浏览记录的显示是从cookie里读出来,然后解析成json,生成html元素。因为用户可能会同时打开好几个页面,这几个页面上可能都有浏览记录,为了使即使显示浏览记录,每秒中刷新一次。
要用到2个js文件,history.js,关键的聊天记录保存和读取代码。json.js,对json进行处理。
history.js
varaddHistory=function(num,id){
stringCookie=getCookie('history');
varstringHistory=""!=stringCookie?stringCookie:"{history:[]}";
varjson=newJSON(stringHistory);
vare="{num:"+num+",id:"+id+"}";
json['history'].push(e);//添加一个新的记录
setCookie('history',json.toString(),30);
}
//显示历史记录
varDisplayHistory=function(){
varp_ele=document.getElementById('history');
while(p_ele.firstChild){
p_ele.removeChild(p_ele.firstChild);
}
varhistoryJSON=getCookie('history');
varjson=newJSON(historyJSON);
vardisplayNum=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元素
varaddLi=function(num,id,pid){
vara=document.createElement('a');
varhref='product.action?pid='+id;
a.setAttribute('href',href);
vart=document.createTextNode(num);
a.appendChild(t);
varli=document.createElement('li');
li.appendChild(a);
document.getElementById(pid).appendChild(li);
}
//添加cookie
varsetCookie=function(c_name,value,expiredays)
{
varexdate=newDate()
exdate.setDate(exdate.getDate()+expiredays)
cookieVal=c_name+"="+escape(value)+((expiredays==null)?"":";expires="+exdate.toGMTString());
//alert(cookieVal);
document.cookie=cookieVal;
}
//获取cookie
functiongetCookie(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>");
returnunescape(document.cookie.substring(c_start,c_end))
}
}
return""
}
json.js
varJSON=function(sJSON){
this.objType=(typeofsJSON);
this.self=[];
(function(s,o){for(variino){o.hasOwnProperty(i)&&(s[i]=o[i],s.self[i]=o[i])};})(this,(this.objType=='string')?eval('0,'+sJSON):sJSON);
}
JSON.prototype={
toString:function(){
returnthis.getString();
},
valueOf:function(){
returnthis.getString();
},
getString:function(){
varsA=[];
(function(o){
varoo=null;
sA.push('{');
for(variino){
if(o.hasOwnProperty(i)&&i!='prototype'){
oo=o[i];
if(ooinstanceofArray){
sA.push(i+':[');
for(varbinoo){
if(oo.hasOwnProperty(b)&&b!='prototype'){
sA.push(oo[b]+',');
if(typeofoo[b]=='object')arguments.callee(oo[b]);
}
}
sA.push('],');
continue;
}else{
sA.push(i+':'+oo+',');
}
if(typeofoo=='object')arguments.callee(oo);
}
}
sA.push('},');
})(this.self);
returnsA.slice(0).join('').replace(/
objectobject
,/ig,'').replace(/,\}/g,'}').replace(/,\]/g,']').slice(0,-1);
},
push:function(sName,sValue){
this.self[sName]=sValue;
this[sName]=sValue;
}
}
希望本文所述对大家JavaScript程序设计有所帮助。