localStorage本地储存编码&&解码存取

localStorage本地储存加密&&解密方法

localStorage 用于长久保存整个网站的数据,保存的数据没有过期时间,直到手动去删除。

注意:
(key存什么名字,取的时候也是什么名字)
有特殊字符或者中文的一定要用加密方法

普通存取

//存
localStorage.setItem('key',"value");
//取
var data = localStorage.getItem("key");
//删除指定
localStorage.removeItem("key");
//删除全部
localStorage.clear();

加密存取

//存
 localStorage.setItem("key",window.btoa(window.encodeURIComponent(JSON.stringify(value))));
//取
var data = JSON.parse(decodeURIComponent(window.atob(localStorage.getItem("key"))));

Window.atob()方法和Window.btoa()方法
atob() 方法用于解码使用 base-64 编码的字符串。
base-64 编码使用方法是 btoa() 。

encodeURIComponent()方法和decodeURIComponent() 方法

encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。
decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。

JSON.stringify()和JSON.parse()
localStorage 只支持 string 类型的存储
JSON.stringify() 方法将 js 对象转换为字符串。
JSON.parse() 方法用于将一个 JSON 字符串转换为对象。

猜你喜欢

转载自blog.csdn.net/qq_42857986/article/details/104825544
今日推荐