日期:2014-05-16 浏览次数:20434 次
// In the following line, you should include the prefixes of implementations you want to test. window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; // DON'T use "var indexedDB = ..." if you're not in a function. // Moreover, you may need references to some window.IDB* objects: window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange // (Mozilla has never prefixed these objects, so we don't need window.mozIDB*) if (!window.indexedDB) { window.alert("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.") }
// Let us open our database var request = window.indexedDB.open("MyTestDatabase"); // open a database with version number var request = indexedDB.open("MyTestDatabase", 3);
var db; var request = indexedDB.open("MyTestDatabase"); request.onerror = function(event) { // Do something with request.errorCode! }; request.onsuccess = function(event) { // Do something with request.result! db = request.result; };
db.onerror = function(event) { // Generic error handler for all errors targeted at this database's // requests! alert("Database error: " + event.target.errorCode); };
// This event is only implemented in recent browsers request.onupgradeneeded = function(event) { // Update object stores and indices .... };
// This is what our customer data looks like. const customerData = [ { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" }, { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" } ]; const dbName = "the_name"; var request = indexedDB.open(dbName, 2); request.onerror = function(event) { // Handle errors. }; request.onupgradeneeded = function(event) { var db = event.target.result; // Create an objectStore to hold information about our customers. We're // going to use "ssn" as our key path because it's guaranteed to be // unique. var objectStore = db.createObjectStore("customers", { keyPath: "ssn" }); // Create an index to search customers by name. We may have duplicates // so we can't use a unique index. objectStore.createIndex("name", "name", { unique: false }); // Create an index to search customers by email. We want to ensure that // no two customers have the same email, so use a unique index. objectStore.createIndex("email", "email", { unique: true }); // Store values in the newly created objectStore. for (var i in customerData) { objectStore.add(customerData[i]); } };
// adding data var transaction = db.transaction(["customers"], "readwrite"); transaction.oncomplete = function(event) { alert("All done!"); }; transaction.onerror = function(event) { // Don't forget to handle errors! }; var objectStore = transaction.objectStore("customers"); for (var i in customerData) { var request = objectStore.add(customerData[i]); requ