📅  最后修改于: 2020-10-23 06:21:06             🧑  作者: Mango
indexeddb是一个新的HTML5概念,用于将数据存储在用户的浏览器中。 indexeddb比本地存储功能强大,对于需要存储大量数据的应用程序很有用。这些应用程序可以运行更高的效率并更快地加载。
W3C宣布Web SQL数据库是已弃用的本地存储规范,因此Web开发人员不应再使用此技术。 indexeddb是Web SQL数据库的替代方法,比旧技术更有效。
在进入indexeddb之前,我们需要添加一些实现的前缀,如下所示
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB ||
window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction ||
window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange ||
window.webkitIDBKeyRange || window.msIDBKeyRange
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
在创建数据库之前,我们必须为数据库准备一些数据。让我们从公司员工详细信息开始。
const employeeData = [
{ id: "01", name: "Gopal K Varma", age: 35, email: " " },
{ id: "02", name: "Prasad", age: 24, email: "prasad@tutorialspoint.com" }
];
这里手动将一些数据添加到数据中,如下所示-
function add() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.add({ id: "01", name: "prasad", age: 24, email: "prasad@tutorialspoint.com" });
request.onsuccess = function(event) {
alert("Prasad has been added to your database.");
};
request.onerror = function(event) {
alert("Unable to add data\r\nPrasad is already exist in your database! ");
}
}
我们可以使用get()从数据库中检索数据
function read() {
var transaction = db.transaction(["employee"]);
var objectStore = transaction.objectStore("employee");
var request = objectStore.get("00-03");
request.onerror = function(event) {
alert("Unable to retrieve daa from database!");
};
request.onsuccess = function(event) {
if(request.result) {
alert("Name: " + request.result.name + ", Age:
" + request.result.age + ", Email: " + request.result.email);
} else {
alert("Kenny couldn't be found in your database!");
}
};
}
与get()一起使用,我们可以将数据存储在对象中,而不是将数据存储在游标中,并且可以从游标中检索数据。
function readAll() {
var objectStore = db.transaction("employee").objectStore("employee");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for id " + cursor.key + " is " + cursor.value.name + ",
Age: " + cursor.value.age + ", Email: " + cursor.value.email);
cursor.continue();
} else {
alert("No more entries!");
}
};
}
我们可以使用remove()从IndexedDB中删除数据。代码如下所示
function remove() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.delete("02");
request.onsuccess = function(event) {
alert("prasad entry has been removed from your database.");
};
}
为了显示所有数据,我们需要使用onClick事件,如下代码所示:
IndexedDb Demo | onlyWebPro.com
最终代码应为-
它将产生以下输出-