js操作cookie保存浏览记录的方法

所属分类: 网络编程 / JavaScript 阅读数: 624
收藏 0 赞 0 分享

本文实例讲述了js操作cookie保存浏览记录的方法。分享给大家供大家参考,具体如下:

说明:最近做了一个功能,记录用户浏览过的产品页面。我的思路是,客户每次进入产品页面,就自己调用JS把产品信息以json的形式保存到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.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程序设计有所帮助。

更多精彩内容其他人还在看

Canvas实现放射线动画效果

本文主要分享了Canvas实现放射线动画的示例代码。具有很好的参考价值,下面跟着小编一起来看下吧
收藏 0 赞 0 分享

微信小程序 image组件binderror使用例子与js中的onerror区别

这篇文章主要介绍了微信小程序 image组件binderror使用例子与js中的onerror区别的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

原生js轮播(仿慕课网)

本文主要分享了原生js实现仿慕课网的轮播效果。具有很好的参考价值,下面跟着小编一起来看下吧
收藏 0 赞 0 分享

Bootstrap table简单使用总结

这篇文章主要为大家总结了Bootstrap table的简单使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

微信小程序之MaterialDesign--input组件详解

本篇文章主要介绍了微信小程序之MaterialDesign--input组件详解,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
收藏 0 赞 0 分享

浅析javaScript中的浅拷贝和深拷贝

本篇文章主要介绍了浅析javaScript中的浅拷贝和深拷贝,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

js时间戳和c#时间戳互转方法(推荐)

下面小编就为大家带来一篇js时间戳和c#时间戳互转方法(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Bootstrap模态框使用详解

这篇文章主要为大家详细介绍了Bootstrap模态框的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Jil,高效的json序列化和反序列化库

下面小编就为大家带来一篇Jil,高效的json序列化和反序列化库。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

BootStrap实现带关闭按钮功能

这篇文章主要介绍了BootStrap实现带关闭按钮功能,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多