这里有indexeddb的一些使用,各种操作基本都包括,有的被注释
var key = null;
// Simply open the database once so that it is created with the required tables
$.indexedDB("MyECommerceSite", {
"schema": {
"1": function(versionTransaction){
var catalog = versionTransaction.createObjectStore("catalog", {
"keyPath": "itemId"
});
catalog.createIndex("price");
},
// This was added in the next version of the site
"2": function(versionTransaction){
var cart = versionTransaction.createObjectStore("cart", {
"autoIncrement": true
});
cart.createIndex("itemId");
var wishlist = versionTransaction.createObjectStore("wishlist", {
"autoIncrement": false,
"keyPath": "itemId"
});
wishlist.createIndex("name");
}
}
}).done(function(){
// Once the DB is opened with the object stores set up, show data from all tables
window.setTimeout(function(){
loadFromDB("cart");
loadFromDB("wishlist");
downloadCatalog();
}, 200);
});
$.indexedDB("www.huffmans.cn", {
"schema": {
"1": function(versionTransaction){
var oflb = versionTransaction.createObjectStore("oflb", {
//"keyPath": "name",
//"autoIncrement": true //do pk
});
oflb.createIndex("name"); //support mutiples index
}
}
}).done(function(){
// Once the DB is opened with the object stores set up, show data from all tables
window.setTimeout(function(){
//loadFromDB("cart");
//loadFromDB("wishlist");
//downloadCatalog();
downloadxml();
//setTimeout(loadFromOflb('oflb'),200);
//updoflb2('oflb');
//loadFromOflb('oflb');
usedbidx();
}, 200);
});
function downloadxml(){
var setting = {
url:'<%=basePath%>github/indexdb/tdata/catalog.json',
type:'get',dataType:'json',async:false,
success:function(data){
$.indexedDB('www.huffmans.cn').transaction('oflb').then(function(){//*READ_ONLY* ,*READ_WRITE* // 0 or 1
console.log("Transaction completed, all data inserted ===");
//loadFromDB("catalog");
}, function(err, e){
console.log("Transaction NOT completed ===", err, e);
},function(transaction){
var oflb = transaction.objectStore('oflb');
$.each(data,function(){
//alert(JSON.stringify(this));
oflb.add(this,this.name);
});
oflb.put({ // is not update
"itemId": 10012,
"name": "ljdd",
"description": "Asd normal looking desktop computer",
"price": 10022,
"rating": 222
},'Desktop');
});},
error:function(xhr,ts,et){alert(et);}
};
$.ajax(setting);
}
function loadFromOflb(table){
$.indexedDB("www.huffmans.cn").objectStore(table).get('Desktop').then(function(data){
alert(JSON.stringify(data));
});
/*
$.indexedDB("www.huffmans.cn").objectStore(table).each(function(elem){
//addRowInHTMLTable(table, elem.key, elem.value);
console.log(elem.key+':'+elem.value);
});
* */
}
function updoflb(table){
$.indexedDB("www.huffmans.cn").objectStore(table).put({
"itemId": 1001,
"name": "lj",
"description": "A normal looking desktop computer",
"price": 100,
"rating": 2
},'Desktop').done(function(result, event){
//result; // Result of the operation. Some operations like delete will return undefined
//event; // Success Event
alert('==');
//if(event){alert('oks');}
}
).fail(function(error, event){
alert(error);
//error; // Type of error that has occured
//event; // Error event
//event.type; // indicates if there was an error or an exception
});
}
function updoflb2(table){
//$.indexedDB("www.huffmans.cn").objectStore(table).delete('Desktop');
//$.indexedDB("www.huffmans.cn").objectStore(table).add('Desktop',{'name':'lij'});
$.indexedDB('www.huffmans.cn').transaction('oflb').then(function(){
console.log("Transaction completed, all data inserted ===");
//loadFromDB("catalog");
}, function(err, e){
console.log("Transaction NOT completed ===", err, e);
},function(transaction){
var oflb = transaction.objectStore('oflb');
//$.each(data,function(){
//alert(JSON.stringify(this));
oflb.put({ // is not update
"itemId": 10012,
"name": "ljdd",
"description": "Asd normal looking desktop computer",
"price": 10022,
"rating": 222
},'lj');
//});
});
/*
$.indexedDB("www.huffmans.cn").objectStore(table).each(function(data){
//alert(JSON.stringify(data));
if(data.key=='Desktop')
data.update({
"itemId": 10012,
"name": "lj",
"description": "Asd normal looking desktop computer",
"price": 10022,
"rating": 222
});
});
* */
}
function usedbidx(){
$.indexedDB('www.huffmans.cn').transaction('oflb').then(function(){//*READ_ONLY* ,*READ_WRITE* // 0 or 1
console.log("Transaction completed, all data inserted ===");
//loadFromDB("catalog");
}, function(err, e){
console.log("Transaction NOT completed ===", err, e);
},function(transaction){
transaction.objectStore('oflb').count().done(function(result,event){alert(result);}); // total is result
//alert($(oflbc).length);
transaction.objectStore('oflb').clear();//.done(function(result,event){alert(result);});
//oflbc = transaction.objectStore('oflb').count();
//alert(transaction.objectStore('oflb').count());
var oflb = transaction.objectStore('oflb').index('name').eachKey(function(item){ //each fn include :k,v
//console.log(item+'<<');//+'<<'+item.key);
});
/*
$.each(data,function(){
//alert(JSON.stringify(this));
oflb.add(this,this.name);
});
oflb.put({ // is not update
"itemId": 10012,
"name": "ljdd",
"description": "Asd normal looking desktop computer",
"price": 10022,
"rating": 222
},'Desktop');
* */
});
}
function deleteDB(){
// Delete the database
$.indexedDB("MyECommerceSite").deleteDatabase();
}
// Download a catalog from the server and save it to the DB
function downloadCatalog(){
$.getJSON("<%=basePath%>github/indexdb/tdata/catalog.json", function(data){
$.indexedDB("MyECommerceSite").transaction("catalog").then(function(){
console.log("Transaction completed, all data inserted");
loadFromDB("catalog");
}, function(err, e){
console.log("Transaction NOT completed", err, e);
}, function(transaction){
var catalog = transaction.objectStore("catalog");
catalog.clear();
$.each(data, function(i){
_(catalog.add(this));
})
});
});
}
// Iterate over each record in a table and display it
function loadFromDB(table){
//emptyTable(table);
_($.indexedDB("MyECommerceSite").objectStore(table).each(function(elem){
//addRowInHTMLTable(table, elem.key, elem.value);
}));
}
function updoflib(table){
$.indexedDB("MyECommerceSite").objectStore(table)
}
// Sort a table based on an index that is setup
function sort(table, key){
//emptyTable(table);
_($.indexedDB("MyECommerceSite").objectStore(table).index(key).each(function(elem){
//addRowInHTMLTable(table, elem.key, elem.value);
}));
}
function emptyDB(table){
_($.indexedDB("MyECommerceSite").objectStore(table).clear());
}
// Read an item from catalog and save it in cart
function addToCart(itemId){
$.indexedDB("MyECommerceSite").objectStore("catalog").get(itemId).then(function(item){
$.indexedDB("MyECommerceSite").objectStore("cart").add(item).done(function(){
loadFromDB("cart");
});
}, function(err, e){
alert("Could not add to cart");
});
}
// Delete an item from cart
function removeFromCart(itemId){
$.indexedDB("MyECommerceSite").objectStore("cart")["delete"](itemId).done(function(){
loadFromDB("cart");
});
}
// Using transactions, read object from cart, add it to wishlist if it does not exist
// and then delete it from the cart. If any operation failes, all these will fail
function moveToWishlist(cartId){
var transaction = $.indexedDB("MyECommerceSite").transaction(["cart", "wishlist"]);
transaction.done(function(){
loadFromDB("cart");
loadFromDB("wishlist");
});
transaction.progress(function(transaction){
transaction.objectStore("cart").get(cartId).done(function(item){
transaction.objectStore("wishlist").add(item).fail(function(){
alert("Already in the wishlist");
}).done(function(){
_(transaction.objectStore("cart")["delete"](cartId));
});
})
});
}
// Read an item from catalog and add it to wishlist
function addToWishlist(itemId){
$.indexedDB("MyECommerceSite").objectStore("catalog").get(itemId).then(function(item){
$.indexedDB("MyECommerceSite").objectStore("wishlist").add(item).done(function(){
loadFromDB("wishlist");
})
}, function(err, e){
alert("Could not add to cart");
});
}
function removeFromWishList(itemId){
$.indexedDB("MyECommerceSite").objectStore("wishlist")["delete"](itemId).done(function(){
loadFromDB("wishlist");
});
}
function renderJSON(val){
var result = [];
for (var key in val) {
result.push("<div class = 'keyval'>");
result.push("<span class = 'key'>", key, "</span>");
result.push("<span class = 'value'>", JSON.stringify(val[key]), "</span>");
result.push("</div>")
}
return result.join("");
}
function _(promise){
promise.then(function(a, e){
console.log("Action completed", e.type, a, e);
}, function(a, e){
console.log("Action completed", a, e);
}, function(a, e){
console.log("Action completed", a, e);
})
}
##########
catalog.json
[{
"itemId": 1001,
"name": "Desktop",
"description": "A normal looking desktop computer",
"price": 100,
"rating": 2
}, {
"itemId": 1002,
"name": "Laptop",
"description": "A laptop computer",
"price": 200,
"rating": 4
}, {
"itemId": 1003,
"name": "Tablet",
"description": "A tablet computer",
"price": 150,
"stock": 4
}, {
"itemId": 1004,
"name": "Embedded",
"description": "Whatever",
"stock": 4
}, {
"itemId": 1005,
"name": "EInk Reader",
"description": "Like a tablet, but different screen",
"price": 150,
"stock": 4
}, {
"itemId": 1006,
"name": "Phone",
"description": "No more a computer",
"price": 250,
"stock": 4
}, {
"itemId": 1007,
"name": "Music players",
"description": "the outer imits ? ",
"price": 10,
"stock": 4
}]
##########
官方api
Jquery-IndexedDB API Reference =============================== List of APIs - Quick Reference * [$.indexedDB()] (#openDatabase) * [$.indexedDB(, schema)] (#openDatabaseUpgrade) * [$.indexedDB().transaction()] (#transactionSec) * [$.indexedDB().objectStore()] (#objectStore) * [$.indexedDB().objectStore().add()] (#crud) * [$.indexedDB().objectStore().each()] (#cursorEach) * [$.indexedDB().objectStore().index()] (#index) * [$.indexedDB().objectStore().deleteDatabase()] (#deleteDatabase) IndexedDB - Quick Intro ------------------------- * [IndexedDB] (http://www.w3.org/TR/IndexedDB/) is a database inside a browser to save and retrieve objects on the browser/client. * IndexedDB contains multiple `objectStores` (sort of tables) that contain data. * `objectStores` have data records in form of (key, javascript object) pairs. (key) uniquely identify records * Data can be written to, read from, or iterated over, inside and `object store` * (key, javascript object) pairs can also have indexes on a property in the (javascript object) * Data operations can be scoped into transactions. Open Database <a name = "openDatabase"/> ---------------------------------------- Creates a new connection to the _Indexed Database_ specified as the name. ``` javascript var dbOpenPromise = $.indexedDB("database_name", { // The second parameter is optional "version" : 3, // Integer version that the DB should be opened with "upgrade" : function(transaction){ // Function called when DB is of lower version that specified in the version parameter // See transaction for details on the argument }, "schema" : { "1" : function(transaction){ // List of instructions to run when DB version is upgraded to 1. // See transaction for details on the argument }, "2" : function(transaction){ // Examples of using the transaction object var obj1 = transaction.objectStore("store1"); var obj2 = transaction.createObjectStore(store2); obj1.createIndex("index"); } } }); ``` <a name = "openDatabaseUpgrade"/> When a `schema` parameter is specified, and if the DB is originally at version `1`, then only functions labeled `2` and above are executed. This provides a way to migrate database by creating object stores, indexes or even reading/writing data between database versions. For details on the `transaction` parameter, looks at the [Transaction] (#trans) object returned during a transaction. Note that the `createObjectStore` and the `deleteObjectStore` are available only during the upgrade operations. Also, `objectStores` opened during progress can have `index` operations. See the [indexes] (#index) section for more details If the optional parameter is not specified, it simply opens the database to the latest version available. It returns a [Jquery Promise] ("http://api.jquery.com/category/deferred-object/") with the following [done] (#dbOpenDone), [progress] (#dbOpenProgress) and [fail] (#dbOpenFail) event handlers. ### Handling Database open success <a name = "dbOpenDone"/> ``` javascript dbOpenPromise.done(function(db, event){ // Called when the database is successfully opened. db; // the native IndexedDB Database object (aka result of the IDBRequest) , event; // the IndexedDB Event object. this; // Context inside the function is the native IDBRequest. }); ``` ### When the database open is in progress <a name = "dbOpenProgress"/> When that database is being upgraded or is blocked due to another transaction being in progress ``` javascript dbOpenPromise.progress(function(db, event){ // Called when there is the database open is in progress - when it is blocked or is being upgraded error; // is the error object and has more details on what the error is event; // is the IndexedDB Event object event.type; //indicates - blocked or upgrade this; // Context inside the function is the native IDBRequest }); ``` When a database open operation is blocked, you can choose to close the database. When the database is being upgraded, you can perform all actions permitted in the versionChange transaction. ### Handling database open error <a name = "dbOpenFail"/> ``` javascript dbOpenPromise.fail(function(error, event){ // Called when there is an error opening the database. error; //is the error object and has more details on what the error is event; //is the IndexedDB Event object. event.type indicates the type - 'error' or 'exception' this; // Context inside the function is the native IDBRequest }); ``` Transactions <a name = "transactionSec"/> -------------------------- Once a database is opened, read and write transactions can be performed within a transaction. var transactionPromise = $.indexedDB("dbName").transaction(storeNames, mode); `storeNames` is an array of object store names (or a single string object store name) that should be under this transaction. <a name = "transactionMode"/> `mode` is 0 or 1 indication *READ_ONLY* or *READ_WRITE*, similar to [modes] (http://www.w3.org/TR/IndexedDB/#dfn-mode) in the IndexedDB Specification. The returned transaction promise has the following event handlers during the lifetime of the transaction. ### Transaction in progress <a name = "transInProgress"/> ``` javascript transactionPromise.progress(function(trans){ // Called when the transaction has started trans; // Use the methods on the trans object (see below) to perform operations }); ``` <a name = "trans"/> The transaction object passed to the callback when transaction is in progress has the following methods on it. ``` javascript var objectStore = trans.objectStore("objectStoreName"); ``` The following 2 methods are available only when the database is being upgraded. Look at the [Open Database Schema] (#openDatabaseUpgrade) section for details. ``` javascript var objectStore = trans.createObjectStore("objectStoreName", { // Options to create object store. "autoIncrement" : true, // [detaults to true], indicating that the key for this object store should auto increment, "keyPath" : id // the path of key in the object, defaults to key that has to be specified separately }); trans.deleteObjectStore(objectStoreName); ``` See [object stores] (#objectStore) for methods on the `objectStore` returned by the above calls. ### Transaction complete ``` javascript transactionPromise.done(function(event){ // Called when transaction is completed event; // Indicated the transaction complete event. }); ``` ### Transaction fails or is aborted ``` javascript transactionPromise.fail(function(event){ // Called when the transaction is aborted or fails event.type; // indicates the reason for failure being error, exception or abort }); ``` Object Stores <a name = "objectStore"/> ---------------------------------------- Once the database is opened, operations need to be performed on object stores. An object store can be opened inside a [transaction that is in progress] (#transInProgress) or using a shorthand on the `$.indexedDB` object like. ``` javascript var objectStore = $.indexedDB("database_name").objectStore("objectStoreName", /* Optional */ mode ); ``` The `mode` parameter defaults to READ_WRITE and is similar to the `mode` parameter specified during a `transaction`. As a convenience method, if the `mode` is set to `true` (instead of 0 or 1), an object store is created if it does not exist. Internally, the database is closed and opened with a higher version to trigger the version transaction where the object store can be created. <a name = "crud"/> The above expression internally creates a transaction for this object store. The `mode` parameter is optional and similar to the [mode parameter] (#transactionMode) in transactions. The CRUD methods on the object store are ```javascript var promise = objectStore.add(/*Javascript Object*/ value, /*Optional*/ key); // Adds data to the objectStore var promise = objectStore.get(key); Gets the object with the key var promise = objectStore.put(/*Javascript Object*/ value, key); // Updates the object for the specified key var promise = objectStore.delete(key); // Deletes the object with the specified key var promise = objectStore.count(); // Gets all the objects var promise = objectStore.clear(); // Removes all data from the object store; ``` The returned promise can be used to note the success or error of the operations ``` javascript promise.done(function(result, event){ result; // Result of the operation. Some operations like delete will return undefined event; // Success Event }); promise.fail(function(error, event){ error; // Type of error that has occured event; // Error event event.type; // indicates if there was an error or an exception }); ``` <a name = "cursorEach"/> To iterate over the objects inside an object store, use ``` javascript var iterationPromise = objectStore.each(function(item){ // Called for each element during the iteration item.key, item.value; // The key and the value of current object item.delete(); // Deletes the current item item.update(newItem); // Updates the current item with newItem; return; // false - do not continue iteration // integer 'n' - n can be 1,2,... indicating skip next n objects and continue // object - continue to item with object as the next key // default - no return, or undefined return, continue iteration }, /*Optional*/ range, /*Optional*/ direction); iterationPromise.done(function(result, event){ // Iteration completed result ; // null, indicating that there are no more objects for iteration event ; // Success event }) iterationPromise.fail(function(error, event){ error; // Error during iteration event; // Error event, can be exception or event }); ``` `range` limits the results and can be an array like `[lower_limit, upper_limit, can_include_lower, can_include_upper]`. If only one element is specified in the array, it becomes an equals clause. The parameters `can_include_lower` and `can_include_upper` are optional and default to true. In addition to the above CURD operation, `objectStore.index` methods also allow operations using indexes. See [indexes] (#index) for details. Indexes <a name = "index"/> --------------------------- Once a reference to an objectStore is obtained either using `transaction.objectStore()`, `transaction.createObjectStore()` or `$.indexedDB("").objectStore()`, the index object can be used. ``` javascript var index = objectStore.index("indexName"); index.each(function(item){ // Iterate over objects in index // Similar to iterating over objects in an ObjectStore item; // same as iterating over objects (see above) }, /*Optional*/ range, /*Optional */ direction); index.eachKey(function(item){ // Iterate over the keys of the object }); ``` While upgrading a database in the [version change transaction] (openDatabaseUpgrade), indexes can also be created or deleted on an object store. ```javascript // trans is created when a database upgrade is in progress var objectStore = trans.objectStore("objectStoreName"); var index = objectStore.createIndex("object.property" , /*Optional*/ { "unique" : false, // Uniqueness of Index, defaults to false "multiEntry" : false // see explanation below }, /* Optional */ "indexName") objectStore.deleteIndex("indexName"); //returns nothing ``` If the second argument to the `createIndex` function is a string, it is considered to be the name of the index. If no indexName is specified in `createIndex`, the property name is used as indexName This multiEntry flag affects how the index behaves when the result of evaluating the index's key path yields an Array. * If the multiEntry flag is false, then a single record whose key is an Array is added to the index. * If the multiEntry flag is true, then the one record is added to the index for each item in the Array. The key for each record is the value of respective item in the Array. Delete Database <a name = "deleteDatabase"/> ------------------------------- A database can be deleted using ``` javascript var deletePromise = $.indexedDB("database_name").deleteDatabase(); deletePromise.done(function(null, event){ /* Called when the delete is successful*/ event; // The success event }); deletePromise.fail(function(error, event){ /* Called when the delete is successful*/ error; // Reason for the error }); deletePromise.progress(function(db, event){ // Called when the deleting is blocked due to another transaction db; // Database that is opened event.type // Indicates it is blocked, etc. }); ``` Compare Keys --------------------- A convenience method to compare keys in a database. Can be used as `$.indexedDB("dbName").cmp(key1, key2)` and return 1,0 or -1 when key1 is greater than, equal to or less than key2 respectively. Links ------- Some useful links * [IndexedDB W3C Specification] (http://www.w3.org/TR/IndexedDB/) * [IndexedDB API playground and examples] (http://nparashuram.com/IndexedDB) * [My work on IndexedDB] (http://blog.nparashuram.com/search/label/indexeddb)
相关推荐
在浏览器上有两种数据库:webSQL和IndexedDB。但是如果在浏览器上需要用到数据库一般会使用Indexed DB数据库,webSQL基本上已经废弃了,具体原因小伙伴可以下来自己查查。 IndexedDB 是一种底层 API,用于在客户端...
IndexedDB 是一种在浏览器中存储大量结构化数据的离线存储解决方案,支持索引,使得数据检索快速高效。它是Web应用程序本地存储的一种重要技术,尤其适用于需要处理大量数据的复杂应用,比如离线应用、数据密集型...
这篇博文将深入探讨IndexedDB的核心概念、用途以及如何在实际项目中运用。 IndexedDB是一种非关系型数据库,它允许在浏览器中存储大量结构化数据,并支持索引,从而可以高效地查询这些数据。与传统的Web存储如...
**前端存储之IndexedDB详解** 在现代Web应用中,数据存储变得越来越重要,尤其是在离线存储和大数据量处理方面。IndexedDB是浏览器提供的一种客户端存储解决方案,它允许开发者在用户的浏览器上存储大量的结构化...
"浏览器端 indexeddb 封装成更简洁易操作的接口" 这个标题表明我们讨论的主题是关于在Web浏览器环境中对IndexedDB数据库进行的一种优化处理,即创建一个用户友好的API,使得开发者能更方便、高效地进行数据存储和...
IndexedDB 是一种在浏览器中存储大量结构化数据的低级 API,它提供了索引和查询功能,非常适合客户端缓存。这个名为 "money-clip" 的项目似乎是一个针对 IndexedDB 的轻量级封装库,旨在简化数据管理和缓存策略,...
这篇博文将深入探讨IndexedDB的原理、用途以及如何在实际项目中应用。 IndexedDB是一种异步的、基于键值对的数据库,不同于传统的Web存储(如localStorage和sessionStorage),它提供了更高级别的结构化数据存储...
IndexedDB 是一种在浏览器中存储大量结构化数据的低级离线存储解决方案,支持索引,使得高效查询成为可能。这个技术对Web应用程序尤其有用,因为它允许开发人员创建丰富的、功能丰富的应用程序,即使在没有网络连接...
**JavaScript开发-IndexedDB键值存储** 在JavaScript开发中,数据存储是一个不可或缺的部分。Web应用程序经常需要在用户浏览器上持久化数据,以便在用户关闭和重新打开页面时保持数据。传统的浏览器存储方式如...
这个通信录的实现就是利用IndexedDB进行数据管理和交互的一个实例。 首先,我们需要理解IndexedDB的基本概念。IndexedDB是一个键值对存储系统,其中每个键都对应一个值。值可以是任意JavaScript类型,包括对象。...
前段时间项目需要本地存储聊天数据,使用到indexedDB,经查阅大量文章,终于完成。感觉网上indexedDB的文章不够多,也不够完善,因此把代码分享出来,帮助需要的小伙伴。
IndexedDB 基本使用
IndexedDB的设计目标是为了满足Web应用程序对大量数据管理的需求,比如离线应用、数据密集型Web应用等。 ### IndexedDB的基本概念 1. **数据库(Database)**:IndexedDB的核心是数据库,每个数据库都有一个唯一的...
Dexie.js是一个轻量级的JavaScript库,它为浏览器中的IndexedDB提供了一个易用且强大的API。IndexedDB是Web浏览器提供的一个原生的本地存储解决方案,允许应用程序在客户端存储大量数据。然而,由于其复杂的API,...
lovefield 是建立在 IndexedDB 上的关系查询引擎。它提供了类似 SQL 的语法,并且可以跨浏览器工作(目前支持 Chrome 37 及以上版本,Firefox 31 及以上版本,IE 10 及以上版本)。示例代码:<!doctype html> <...
IndexedDB是Web应用程序的一个重要组成部分,它是一种在浏览器中存储大量结构化数据的离线存储解决方案。这个压缩包“IndexedDB基本使用共22页.pdf.zip”包含了22页关于IndexedDB的基础教程,旨在帮助开发者理解和...
1. 安装npm包// use npmnpm install --save-dev indexeddb-promise// use yarnyarn add --dev indexeddb-promisescript引入IndexedDB 会被注册为一个全局变量。建议链接到一个可以手动更新的指定版本号:[removed]...
**IndexedDB 详解** IndexedDB 是一种在浏览器中存储大量数据的离线存储技术,它为Web应用程序提供了数据库的功能。这个技术尤其适用于那些需要在本地存储大量结构化数据的应用,如离线阅读应用、Web邮件客户端或者...