前言
后端经常使用数据库作数据存储,譬如MySql
、MongoDB
,缓存技术存储数据,如Redis
、Memcached
;javascript
前端存储数据目前经常使用的是Cookie
、Storage
、IndexedDB
html
Cookie
HTTP Cookie
(也叫Web Cookie
或浏览器Cookie
)是服务器发送到用户浏览器并保存在本地的一小块数据,它会在浏览器下次向同一服务器再发起请求时被携带并发送到服务器上。一般,它用于告知服务端两个请求是否来自同一浏览器,如保持用户的登陆状态。Cookie
使基于无状态的HTTP
协议记录稳定的状态信息成为了可能。前端
分类
Cookie
老是保存在客户端中(早期Java
中常常会将Cookie
与Session
做为存储技术进行比较,Session
是将数据保存在服务器端,大量的数据存储会增长服务器的负担),按在客户端中的存储位置,可分为内存Cookie
和硬盘Cookie
。
内存Cookie
由浏览器维护,保存在内存中,浏览器关闭后就消失了,其存在时间是短暂的。硬盘Cookie
保存在硬盘里,有一个过时时间,除非用户手工清理或到了过时时间,硬盘Cookie
不会被删除,其存在时间是长期的。因此,按存在时间,可分为非持久Cookie
和持久Cookie
。java
建立Cookie
Set-Cookie
响应头部和Cookie
请求头部节
服务器使用Set-Cookie
响应头部向用户代理(通常是浏览器)发送Cookie
信息。一个简单的Cookie
可能像这样:Set-Cookie: <cookie名>=<cookie值>
web
服务器经过该头部告知客户端保存Cookie
信息数据库
浏览器环境下获取非HttpOnly
标记的 cookie
后端
var cookies = document.cookie;复制代码复制代码
Cookie的缺点
Cookie
会被附加在每一个HTTP
请求中,因此无形中增长了流量。因为在HTTP
请求中的Cookie
是明文传递的,因此安全性成问题,除非用HTTPS
。api
Cookie
的大小限制在4KB
左右,对于复杂的存储需求来讲是不够用的。浏览器
Cookie的简单封装
设置Cookie
时通常会将路径和过时时间一并设置,注意过时时间须要转换成GMT
或者UTC
缓存
代码
(function IIFE(root){
function getCookie(cname, defaultValue){
var value = new RegExp('(^|;| )'+cname+'=([^;]*?)(;|$)', 'g').exec(document.cookie);
console.log('value:', value);
if(!value) return defaultValue;
return value[2];
}
function setCookie(cname, cvalue, day, path){
day = day || 1;
path = path || '/';
var date = new Date();
date.setTime(date.getTime() + day * 24 * 60 * 60 * 1000);
document.cookie = cname+'='+cvalue+'; expires=' + date.toGMTString() + '; path='+path+'; ';
}
function deleteCookie(cname){
setCookie(cname, null, -1);
}
root.Util = {
getCookie: getCookie,
setCookie: setCookie,
deleteCookie: deleteCookie,
}
})(window);复制代码复制代码
测试结果
Storage
做为 Web Storage API
的接口,Storage
提供了访问特定域名下的会话存储(session storage
)或本地存储(local storage
)的功能,例如,能够添加、修改或删除存储的数据项。
若是你想要操做一个域名的会话存储(session storage
),能够使用 window.sessionStorage
若是想要操做一个域名的本地存储(local storage
),能够使用 window.localStorage
。
sessionStorage
和localStorage
的用法是同样的,区别在于sessionStorage
会在会话关闭也就是浏览器关闭时失效,而localStorage
是将数据存储在本地,不受关闭浏览器影响,除非手动清除数据
相关的api你们能够参考
developer.mozilla.org/zh-CN/docs/…
代码
(function IIFE(){
if(!window.localStorage){
alert('your browser is not support localStorage!');
return;
}
function getStorage(sname, defaultValue){
//result = window.localStorage.sname
//result = window.localStorage[sname]
var result = window.localStorage.getItem(sname);
return result || defaultValue;
}
function setStorage(sname, svalue){
window.localStorage.setItem(sname, svalue);
}
function removeItem(sname){
window.localStorage.removeItem(sname);
}
function getKey(keyIndex){
return window.localStorage.key(keyIndex);
}
function getAllKeys(){
var arr = [];
for(var i=0;i<window.localStorage.length;i++){
arr.push(window.localStorage.key(i));
}
return arr;
}
function clearStorage(){
window.localStorage.clear();
}
function onStorageChange(event){
console.log(event)
}
window.addEventListener('storage', onStorageChange);
window.Util = {
getStorage: getStorage,
setStorage: setStorage,
removeItem: removeItem,
getKey: getKey,
getAllKeys: getAllKeys,
clearStorage: clearStorage,
}
})();复制代码复制代码
测试结果
IndexedDB
随着浏览器的功能不断加强,愈来愈多的网站开始考虑,将大量数据储存在客户端,这样能够减小从服务器获取数据,直接从本地获取数据。
现有的浏览器数据储存方案,都不适合储存大量数据:Cookie
的大小不超过 4KB
,且每次请求都会发送回服务器;LocalStorage
在 2.5MB
到 10MB
之间(各家浏览器不一样),并且不提供搜索功能,不能创建自定义的索引。因此,须要一种新的解决方案,这就是 IndexedDB
诞生的背景。
通俗地说,IndexedDB
就是浏览器提供的本地数据库,它能够被网页脚本建立和操做。IndexedDB
容许储存大量数据,提供查找接口,还能创建索引。这些都是 LocalStorage
所不具有的。就数据库类型而言,IndexedDB
不属于关系型数据库(不支持 SQL
查询语句),更接近 NoSQL
数据库。
IndexedDB
相关API
可参考
代码
(function IIFE(){
if(!window.indexedDB){
alert('your browser is not support indexedDB!');
return;
}
var request = window.indexedDB.open('person', 1);
var db;
request.onerror = function (event) {
console.log('数据库打开报错');
};
request.onsuccess = function (event) {
db = request.result;
console.log('数据库打开成功');
};
request.onupgradeneeded = function(event) {
console.log('onupgradeneeded...');
db = event.target.result;
var objectStore = db.createObjectStore('person', { keyPath: 'id' });
objectStore.createIndex('name', 'name', { unique: false });
objectStore.createIndex('email', 'email', { unique: true });
}
function add(obj) {
var request = db.transaction(['person'], 'readwrite')
.objectStore('person')
.add(obj)
//.add({ id: 1, name: 'ccy', age: 18, email: 'test@example.com' });
request.onsuccess = <span class="hljs-keyword">function</span> (event) {
console.log(<span class="hljs-string">'数据写入成功'</span>);
};
request.onerror = <span class="hljs-keyword">function</span> (event) {
console.log(<span class="hljs-string">'数据写入失败'</span>);
}
}
<span class="hljs-keyword">function</span> <span class="hljs-built_in">read</span>(index) {
var transaction = db.transaction([<span class="hljs-string">'person'</span>]);
var objectStore = transaction.objectStore(<span class="hljs-string">'person'</span>);
var request = objectStore.get(index);
request.onerror = <span class="hljs-keyword">function</span>(event) {
console.log(<span class="hljs-string">'事务失败'</span>);
};
request.onsuccess = <span class="hljs-keyword">function</span>(event) {
<span class="hljs-keyword">if</span> (request.result) {
console.log(<span class="hljs-string">'Name: '</span> + request.result.name);
console.log(<span class="hljs-string">'Age: '</span> + request.result.age);
console.log(<span class="hljs-string">'Email: '</span> + request.result.email);
} <span class="hljs-keyword">else</span> {
console.log(<span class="hljs-string">'未得到数据记录'</span>);
}
};
}
<span class="hljs-keyword">function</span> <span class="hljs-function"><span class="hljs-title">readAll</span></span>() {
var objectStore = db.transaction(<span class="hljs-string">'person'</span>).objectStore(<span class="hljs-string">'person'</span>);
objectStore.openCursor().onsuccess = <span class="hljs-keyword">function</span> (event) {
var cursor = event.target.result;
<span class="hljs-keyword">if</span> (cursor) {
console.log(<span class="hljs-string">'Id: '</span> + cursor.key);
console.log(<span class="hljs-string">'Name: '</span> + cursor.value.name);
console.log(<span class="hljs-string">'Age: '</span> + cursor.value.age);
console.log(<span class="hljs-string">'Email: '</span> + cursor.value.email);
cursor.continue();
} <span class="hljs-keyword">else</span> {
console.log(<span class="hljs-string">'没有更多数据了!'</span>);
}
};
}
<span class="hljs-keyword">function</span> update(obj) {
var request = db.transaction([<span class="hljs-string">'person'</span>], <span class="hljs-string">'readwrite'</span>)
.objectStore(<span class="hljs-string">'person'</span>)
.put(obj)
//.put({ id: 1, name: <span class="hljs-string">'李四'</span>, age: 35, email: <span class="hljs-string">'lisi@example.com'</span> });
request.onsuccess = <span class="hljs-keyword">function</span> (event) {
console.log(<span class="hljs-string">'数据更新成功'</span>);
};
request.onerror = <span class="hljs-keyword">function</span> (event) {
console.log(<span class="hljs-string">'数据更新失败'</span>);
}
}
<span class="hljs-keyword">function</span> remove(index) {
var request = db.transaction([<span class="hljs-string">'person'</span>], <span class="hljs-string">'readwrite'</span>)
.objectStore(<span class="hljs-string">'person'</span>)
.delete(index);
request.onsuccess = <span class="hljs-keyword">function</span> (event) {
console.log(<span class="hljs-string">'数据删除成功'</span>);
};
}
window.util = {
add: add,
<span class="hljs-built_in">read</span>: <span class="hljs-built_in">read</span>,
<span class="hljs-built_in">read</span>All: <span class="hljs-built_in">read</span>All,
update: update,
remove: remove,
}
复制代码
复制代码request.onsuccess = <span class="hljs-keyword">function</span> (event) {
console.log(<span class="hljs-string">'数据写入成功'</span>);
};
request.onerror = <span class="hljs-keyword">function</span> (event) {
console.log(<span class="hljs-string">'数据写入失败'</span>);
}
}
<span class="hljs-keyword">function</span> <span class="hljs-built_in">read</span>(index) {
var transaction = db.transaction([<span class="hljs-string">'person'</span>]);
var objectStore = transaction.objectStore(<span class="hljs-string">'person'</span>);
var request = objectStore.get(index);
request.onerror = <span class="hljs-keyword">function</span>(event) {
console.log(<span class="hljs-string">'事务失败'</span>);
};
request.onsuccess = <span class="hljs-keyword">function</span>(event) {
<span class="hljs-keyword">if</span> (request.result) {
console.log(<span class="hljs-string">'Name: '</span> + request.result.name);
console.log(<span class="hljs-string">'Age: '</span> + request.result.age);
console.log(<span class="hljs-string">'Email: '</span> + request.result.email);
} <span class="hljs-keyword">else</span> {
console.log(<span class="hljs-string">'未得到数据记录'</span>);
}
};
}
<span class="hljs-keyword">function</span> <span class="hljs-function"><span class="hljs-title">readAll</span></span>() {
var objectStore = db.transaction(<span class="hljs-string">'person'</span>).objectStore(<span class="hljs-string">'person'</span>);
objectStore.openCursor().onsuccess = <span class="hljs-keyword">function</span> (event) {
var cursor = event.target.result;
<span class="hljs-keyword">if</span> (cursor) {
console.log(<span class="hljs-string">'Id: '</span> + cursor.key);
console.log(<span class="hljs-string">'Name: '</span> + cursor.value.name);
console.log(<span class="hljs-string">'Age: '</span> + cursor.value.age);
console.log(<span class="hljs-string">'Email: '</span> + cursor.value.email);
cursor.continue();
} <span class="hljs-keyword">else</span> {
console.log(<span class="hljs-string">'没有更多数据了!'</span>);
}
};
}
<span class="hljs-keyword">function</span> update(obj) {
var request = db.transaction([<span class="hljs-string">'person'</span>], <span class="hljs-string">'readwrite'</span>)
.objectStore(<span class="hljs-string">'person'</span>)
.put(obj)
//.put({ id: 1, name: <span class="hljs-string">'李四'</span>, age: 35, email: <span class="hljs-string">'lisi@example.com'</span> });
request.onsuccess = <span class="hljs-keyword">function</span> (event) {
console.log(<span class="hljs-string">'数据更新成功'</span>);
};
request.onerror = <span class="hljs-keyword">function</span> (event) {
console.log(<span class="hljs-string">'数据更新失败'</span>);
}
}
<span class="hljs-keyword">function</span> remove(index) {
var request = db.transaction([<span class="hljs-string">'person'</span>], <span class="hljs-string">'readwrite'</span>)
.objectStore(<span class="hljs-string">'person'</span>)
.delete(index);
request.onsuccess = <span class="hljs-keyword">function</span> (event) {
console.log(<span class="hljs-string">'数据删除成功'</span>);
};
}
window.util = {
add: add,
<span class="hljs-built_in">read</span>: <span class="hljs-built_in">read</span>,
<span class="hljs-built_in">read</span>All: <span class="hljs-built_in">read</span>All,
update: update,
remove: remove,
}
复制代码})();复制代码复制代码
测试结果
后记
浏览器存储技术目前流行的基本就上面介绍的三种,以前出现的webSql
因为用方言SQLlite
致使没法统一,也就是说这是一个废弃的标准。
localStorage
、indexedDB
这里没有作详细的介绍,只是简单的给出示例代码作作演示,不熟悉的能够查阅相关API
。
参考资料
developer.mozilla.org/zh-CN/docs/…
developer.mozilla.org/zh-CN/docs/…
zh.wikipedia.org/wiki/Cookie
www.ruanyifeng.com/blog/2018/0…
wangdoc.com/javascript/…