目前前端存储数据常用的是Cookie
、Storage
、IndexedDB
三种技术。下面将对这三个技术进行简述。
cookie
、localStorage
、sessionStorage
、IndexedDB
之间的区别
cookie
数据始终在同源的http请求中携带(即使不需要),即cookie在浏览器和服务器间来回传递。而sessionStorage
和localStorage
不会自动把数据发给服务器,仅在本地保存。cookie数据还有路径(path)的概念,可以限制cookie只属于某个路径下。存储大小限制
不同,cookie
数据不能超过4k,同时因为每次http请求都会携带cookie,所以cookie只适合保存很小的数据,如会话标识。sessionStorage
和localStorage
虽然也有存储大小的限制,但比cookie大得多,可以达到5M或更大。数据有效期
不同,sessionStorage
:仅在当前浏览器窗口关闭前有效,自然也就不可能持久保持;localStorage
:始终有效,窗口或浏览器关闭也一直保存,因此用作持久数据;cookie
只在设置的cookie过期时间之前一直有效,即使窗口或浏览器关闭。作用域
不同,sessionStorage
不在不同的浏览器页面中共享,即使是同一个页面;localStorage
在所有同源窗口中都是共享的;cookie
也是在所有同源窗口中都是共享的。IndexedDB
是浏览器提供的本地数据库,它可以被网页脚本创建和操作。IndexedDB 允许储存大量数据,提供查找接口,还能建立索引。这些都是 Storage 所不具备的。就数据库类型而言,IndexedDB 不属于关系型数据库(不支持 SQL 查询语句),更接近 NoSQL 数据库。
一、Cookie
(function init_Cuiht_cookie() {
function get(cname) {
var result = new RegExp("(^|;| )" + cname + "=([^;]*?)(;|$)", "g").exec(
document.cookie
);
if (!result) return "";
try {
result = JSON.parse(result[2]);
} catch (error) {
result = result[2];
}
return result;
}
function set(cname, cvalue, day, path) {
day = day || 7;
path = path || "/";
var date = new Date();
date.setTime(date.getTime() + day * 24 * 60 * 60 * 1000);
try {
cvalue = JSON.stringify(cvalue);
} catch (error) {}
document.cookie =
cname +
"=" +
cvalue +
"; expires=" +
date.toGMTString() +
"; path=" +
path +
"; ";
}
function del(cname) {
set(cname, null, -1);
}
window.CHT_cookie = {
get: get,
set: set,
del: del,
};
})();
- 使用示例
// 设置数据
CHT_cookie.set("cuiht_test_cookie", {
name: "cuiht",
age: 18,
sex: 0,
});
// 获取数据
console.log(CHT_cookie.get("cuiht_test_cookie"));
// 删除数据
CHT_cookie.del("cuiht_test_cookie");
二、Storage
// localStorage
(function init_Cuiht_localStorage() {
if (!window.localStorage) {
alert("your browser is not support localStorage!");
return;
}
function get(sname) {
var result = window.localStorage.getItem(sname);
try {
result = JSON.parse(result);
} catch (error) {}
return result;
}
function set(sname, svalue) {
try {
svalue = JSON.stringify(svalue);
} catch (error) {}
window.localStorage.setItem(sname, svalue);
}
function del(sname) {
window.localStorage.removeItem(sname);
}
function clear() {
window.localStorage.clear();
}
function getAllKeys() {
var arr = [];
for (var i = 0; i < window.localStorage.length; i++) {
arr.push(window.localStorage.key(i));
}
return arr;
}
window.CHT_localStorage = {
get: get,
set: set,
del: del,
clear: clear,
getAllKeys: getAllKeys,
};
})();
// sessionStorage
(function init_Cuiht_sessionStorage() {
if (!window.sessionStorage) {
alert("your browser is not support sessionStorage!");
return;
}
function get(sname) {
var result = window.sessionStorage.getItem(sname);
try {
result = JSON.parse(result);
} catch (error) {}
return result;
}
function set(sname, svalue) {
try {
svalue = JSON.stringify(svalue);
} catch (error) {}
window.sessionStorage.setItem(sname, svalue);
}
function del(sname) {
window.sessionStorage.removeItem(sname);
}
function clear() {
window.sessionStorage.clear();
}
function getAllKeys() {
var arr = [];
for (var i = 0; i < window.sessionStorage.length; i++) {
arr.push(window.sessionStorage.key(i));
}
return arr;
}
window.CHT_sessionStorage = {
get: get,
set: set,
del: del,
clear: clear,
getAllKeys: getAllKeys,
};
})();
- 使用示例
// localStorage部分
// 设置数据
CHT_localStorage.set("cuiht_test_localStorage", {
name: "cuiht",
age: 18,
sex: 0,
});
// 获取数据
console.log(CHT_localStorage.get("cuiht_test_localStorage"));
// 获取数据所有键名
console.log(CHT_localStorage.getAllKeys());
// 删除数据
CHT_localStorage.del("cuiht_test_localStorage");
// 清楚所有数据
CHT_localStorage.clear();
// sessionStorage部分
// 设置数据
CHT_sessionStorage.set("cuiht_test_sessionStorage", {
name: "cuiht",
age: 18,
sex: 0,
});
// 获取数据
console.log(CHT_sessionStorage.get("cuiht_test_sessionStorage"));
// 获取数据所有键名
console.log(CHT_sessionStorage.getAllKeys());
// 删除数据
CHT_sessionStorage.del("cuiht_test_sessionStorage");
// 清楚所有数据
CHT_sessionStorage.clear();
三、indexedDB
(function init_Cuiht_indexedDB() {
if (!window.indexedDB) {
alert("your browser is not support indexedDB!");
return;
}
function Cuiht_indexedDB(option) {
if (!option) {
console.error("请配置合法indexedDB数据库参数");
return;
}
if (!option.dbName) {
console.error("请配置合法indexedDB数据库名");
return;
}
this.dbName = option.dbName;
this.debugger = option.debugger || false;
this.db = "";
this.open(option);
}
// 打开数据库or新建数据库
Cuiht_indexedDB.prototype.open = function (option) {
var that = this,
request = window.indexedDB.open(that.dbName, option.v || 1);
request.onerror = function (event) {
that.console("数据库打开报错");
};
request.onsuccess = function (event) {
that.db = request.result;
that.console("数据库打开成功");
};
request.onupgradeneeded = function (event) {
that.console("onupgradeneeded...");
that.db = event.target.result;
(option.stores || []).forEach((storeConfig) => {
if (!that.db.objectStoreNames.contains(storeConfig.storeName)) {
that.addStore(storeConfig);
}
});
};
};
// 新建仓库
Cuiht_indexedDB.prototype.addStore = function (config) {
if (!config) {
console.error("请配置合法仓库参数");
return;
}
if (!config.storeName) {
console.error("请配置合法仓库名");
return;
}
var that = this,
objectStore = that.db.createObjectStore(config.storeName, {
keyPath: "id",
autoIncrement: true,
});
(config.indexs || []).forEach((index) => {
if (!index.name) {
console.error("请配置合法索引名称名");
return;
}
objectStore.createIndex(index.name, index.attribute || index.name, {
unique: index.unique || false,
});
});
};
// 添加数据
Cuiht_indexedDB.prototype.addData = function (config) {
var that = this;
if (!that.db) {
setTimeout(function () {
that.addData(config);
}, 1);
return;
}
var request = that.db
.transaction([config.storeName], "readwrite")
.objectStore(config.storeName)
.add(config.data);
request.onsuccess = function (event) {
that.console("数据写入成功");
};
request.onerror = function (event) {
console.error(event);
console.error("数据写入失败");
};
};
// 获取指定数据
Cuiht_indexedDB.prototype.getData = function (config, cb) {
var that = this;
if (!that.db) {
setTimeout(function () {
that.getData(config, cb);
}, 1);
return;
}
var request = that.db
.transaction([config.storeName], "readonly")
.objectStore(config.storeName)
.get(config.id);
request.onerror = function (event) {
console.error(event);
console.error("数据读取失败");
};
request.onsuccess = function (event) {
if (request.result) {
if (cb) cb(request.result);
} else {
that.console("未获得数据记录");
}
};
};
// 获取全部数据
Cuiht_indexedDB.prototype.getAll = function (config, cb) {
var that = this;
if (!that.db) {
setTimeout(function () {
that.getAll(config, cb);
}, 1);
return;
}
var objectStore = that.db
.transaction(config.storeName)
.objectStore(config.storeName);
objectStore.openCursor().onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
if (cb) cb(cursor.value);
cursor.continue();
} else {
that.console("全部数据获取完毕!");
}
};
};
Cuiht_indexedDB.prototype.updData = function (config) {
var that = this;
if (!that.db) {
setTimeout(function () {
that.updData(config);
}, 1);
return;
}
var request = that.db
.transaction([config.storeName], "readwrite")
.objectStore(config.storeName)
.put(config.data);
request.onsuccess = function (event) {
that.console("数据更新成功");
};
request.onerror = function (event) {
console.error(event);
console.error("数据更新失败");
};
};
Cuiht_indexedDB.prototype.delData = function (config) {
var that = this;
if (!that.db) {
setTimeout(function () {
that.delData(config);
}, 1);
return;
}
var request = that.db
.transaction([config.storeName], "readwrite")
.objectStore(config.storeName)
.delete(config.id);
request.onsuccess = function (event) {
that.console("数据删除成功");
};
};
Cuiht_indexedDB.prototype.getIndex = function (config, cb) {
var that = this;
if (!that.db) {
setTimeout(function () {
that.getIndex(config, cb);
}, 1);
return;
}
var request = that.db
.transaction([config.storeName], "readonly")
.objectStore(config.storeName)
.index(config.indexName)
.get(config.value);
request.onsuccess = function (event) {
var result = event.target.result;
if (result) {
if (cb) cb(result);
} else {
that.console("未获得数据记录");
}
};
};
Cuiht_indexedDB.prototype.console = function (msg) {
if (this.debugger) {
console.log(msg);
}
};
window.Cuiht_indexedDB = Cuiht_indexedDB;
})();
- 使用示例
// 添加数据
cuiht_indexDB.addData({
storeName: "store1",
data: { id: 20, name: "cuiht1", age: 18, email: "[email protected]" },
});
cuiht_indexDB.addData({
storeName: "store1",
data: { name: "cuiht2", age: 18, email: "[email protected]" },
});
cuiht_indexDB.addData({
storeName: "store1",
data: { name: "cuiht3", age: 18, email: "[email protected]" },
});
// 获取指定数据
cuiht_indexDB.getData(
{
storeName: "store1",
id: 1,
},
function (data) {
console.log(data);
}
);
// 获取全部数据
cuiht_indexDB.getAll(
{
storeName: "store1",
},
function (data) {
console.log(data);
}
);
// 修改数据
cuiht_indexDB.updData({
storeName: "store1",
data: {
id: 1,
name: "cuiht_upt",
age: 18,
email: "[email protected]",
},
});
// 删除数据
cuiht_indexDB.delData({
storeName: "store1",
id: 1,
});
// 根据某个属性获取数据
cuiht_indexDB.getIndex(
{
storeName: "store1",
indexName: "name",
value: "cuiht3",
},
function (data) {
console.log(data);
}
);
没有压力的生命就会黯淡。