使用localStorage替代cookie做本地存储

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

使用localStorage替代cookie做本地存储

longxuu   2020-05-17 我要评论

因为cookie存储有限,加上cookie每次都要上传到服务器,浪费了带宽不说,而且伤害了感情。

基于HTML5的localStorage可能能给你带的新的希望,而且最大支持不超过5MB的数据存储。可惜的是,IE方面只支持IE8以上的版本。

我花了一点时间就最近浏览记录的存储简单的写了一个javascript代码来做演示

late = {
 storage : {},
 isinit : 0,
 maxnum : 10,
 key : 'vestigial',
 _init:function(){
  if (late.isinit === 1) {
   return true;
  } else if (late.isinit === 0 && window.localStorage) {
   late.isinit = 1;
   late.storage = window.localStorage;
   return true;
  } else {
   return false;
  }
 },
 
 get:function(){
  if(late._init()){
   var data = late.storage.getItem(late.key);
   return JSON.parse(data);
  }else{
   return false;
  }
 },
 
 set:function(value){
  if(late._init()){
   var data = late.storage.getItem(late.key); 
   data = JSON.parse(data);
   if(data === null){
    data = [];
   }
   if (data.length === 10) {
    data.shift();
   }
   data.push(value);
   data = JSON.stringify(data);
   late.storage.setItem(late.key, data);
   return true;
  }else{
   return false;
  }
 }
};
 
var obj = {
  id:2, 
  title:'标题1', 
  url:'http://www.baidu.com'
 };
late.set(obj);
var each = late.get();
var eachlength = each.length;
for(i=0; i<eachlength; i++){
 document.writeln(JSON.stringify(each[i]));
}

实在不行的话还可以使用flash来存储,不建议使用cookie。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们