本文介绍利用JavaScript操作Cookie保存用户浏览记录的方法。通过history.js实现产品信息的JSON格式存储与读取,结合json.js处理数据,并每秒刷新一次以实时显示浏览历史。适用于需要记录用户访问路径的前端场景。
JavaScript实现Cookie保存与读取浏览记录
本文详细介绍如何使用JavaScript操作Cookie来保存用户的浏览记录,供读者参考学习。
功能背景与核心思路
功能背景:近期开发了一个记录用户浏览过产品页面的功能。核心思路是,当用户每次进入产品页面时,前端JS自动调用接口,将产品信息以JSON格式写入Cookie中。
数据显示与实时刷新机制
数据显示:从Cookie中读取保存的数据,解析为JSON对象后生成对应的HTML元素进行展示。考虑到用户可能同时打开多个页面,且各页面均包含浏览记录,为了实现浏览记录的实时刷新显示,系统设定每秒执行一次刷新操作。
实现依赖文件说明
实现依赖:该功能需要两个JavaScript文件支持。一是history.js,负责核心的记录保存与读取逻辑;二是json.js,用于处理JSON数据的序列化与反序列化。
history.js文件代码如下:
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文件代码如下:
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(/
objectobject
,/ig,'').replace(/,\}/g,'}').replace(/,\]/g,']').slice(0,-1);
},
push:function(sName,sValue){
this.self[sName] = sValue;
this[sName] = sValue;
}
}
希望上述关于JavaScript程序设计的示例内容能对大家有所帮助。