As mentioned beforehtml5The support for offline applications is very good. It cannot help but support localstorage to store a key-value pair on the client and it can also reference the manifest file. Define the files that need caching in it. In fact, indexdb can also be used in html5, also known as index database. This database can be used to store offline objects. Let’s start:
After all requests are completed, there will be a callback, onsuccess and onerror, where: onsuccess indicates the callback when the request is successful, onerror indicates the request Callback in case of failure. At the same time, you can alsouse try/catch in javascript to catch exceptions for further processing.
A database can only have one version at a time. When the database is first created, the version number is 0. When we need to change the database that has been created, we need to change its version. No., when the version number is changed, the upgradeneeded callback will be triggered, so the method of modifying the database or storage object must be executed in the upgradeneeded method.
if (!window.indexedDB) { window.alert("您的浏览器不支持indexdb"); }<!--这里indexDB是window对象的属性,类似于alert所以window可以省略-->
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript"> function createDatabase(indexDbName) { //调用 open 方法并传递数据库名称。如果不存在具有指定名称的数据库,则会创建该数据库 var openRequest = indexedDB.open(indexDbName); var db; openRequest.onerror = function(e) {//当创建数据库失败时候的回调 console.log("Database error: " + e.target.errorCode); }; openRequest.onsuccess = function(event) { console.log("Database created"); db = openRequest.result;//创建数据库成功时候,将结果给db,此时db就是当前数据库 //alert("this is :"+db); }; openRequest.onupgradeneeded = function (evt) {//更改数据库,或者存储对象时候在这里处理 }; } </script></head><body> <a href="javascript:createDatabase('firstdb')">createDatabase</a></body></html>
The above code can create a database to the client.
Delete an existing database by calling the deleteDatabase method and passing in the name of the database that needs to be deleted.
function deleteDatabase(indexDbName) { var deleteDbRequest = indexedDB.deleteDatabase(indexDbName); deleteDbRequest.onsuccess = function (event) { console.log("detete database success"); }; deleteDbRequest.onerror = function (e) { console.log("Database error: " + e.target.errorCode); }; }
There is no concept of table in indexdb, but objectstore is used to store objects. A database can contain multiple objectStores, and objectStore is A flexible data structure that can store multiple types of data. We can use a specified field in each record as the key value (keyPath), or we can use an automatically generated incrementing number as the key value (keyGenerator), or we can not specify it. Depending on the type of selection key, the data structures that objectStore can store are also different
When updating database content or inserting new data, you need to open the thing first And you need to specify which objectstores the current transaction operates on.
Transactions have three modes
Read-only: read, database data cannot be modified, and can be executed concurrently
read-write : readwrite, can perform read and write operations
Version change: verionchange
Because of the new data All operations need to be performed in a transaction, and the transaction requires the object store to be specified, so we can only initialize the object store when creating the database for later use.
Specify keyid, which can be understood as specifying a primary key
//添加数据 function insertAnObj(indexDbName) { var userinfos=[{ id:1001, name:"小李", age:24 },{ id:1002, name:"老王", age:30 },{ id:1003, name:"王麻子", age:26 }]; var openRequest = indexedDB.open(indexDbName,1); openRequest.onerror = function(e) {//当创建数据库失败时候的回调 console.log("Database error: " + e.target.errorCode); }; openRequest.onsuccess = function(event) { console.log("Database created"); db = openRequest.result; //创建数据库成功时候,将结果给db,此时db就是当前数据库 //alert("this is :"+db); //打开和userinfo相关的objectstore的事物 var transaction = db.transaction("userinfo",'readwrite'); var store=transaction.objectStore("userinfo"); for(var i=0;i<userinfos.length;i++){ //alert("add"+userinfos[i]); store.add(userinfos[i]);//将对象添加至userinfo相关的objectstore中 } }; openRequest.onupgradeneeded = function(event) { var db = event.target.result; //在第一次创建数据库的时候,就创建userinfo相关的objectstore,以供后面添加数据时候使用 if(!db.objectStoreNames.contains('userinfo')){ //keyPath:Javascript对象,对象必须有一属性作为键值 db.createObjectStore('userinfo',{keyPath:"id"}); } } }
Specifying autoIncrement can be understood as specifying a primary key to automatically grow.
//指定主键自动增长 function insertAutoInc(indexDbName) { var userinfos=[{ id:1001, name:"小李", age:24 },{ id:1002, name:"老王", age:30 },{ id:1003, name:"王麻子", age:26 }]; var openRequest = indexedDB.open(indexDbName,2); openRequest.onerror = function(e) {//当创建数据库失败时候的回调 console.log("Database error: " + e.target.errorCode); }; openRequest.onsuccess = function(event) { console.log("Database created"); db = openRequest.result; //创建数据库成功时候,将结果给db,此时db就是当前数据库 //alert("this is :"+db); //打开和userinfo相关的objectstore的事物 var transaction = db.transaction("userinfo",'readwrite'); var store=transaction.objectStore("userinfo"); for(var i=0;i<userinfos.length;i++){ //alert("add"+userinfos[i]); store.add(userinfos[i]);//将对象添加至userinfo相关的objectstore中 } }; openRequest.onupgradeneeded = function(event) { var db = event.target.result; //在第一次创建数据库的时候,就创建userinfo相关的objectstore,以供后面添加数据时候使用 if(!db.objectStoreNames.contains('userinfo')){ //keyPath:Javascript对象,对象必须有一属性作为键值 db.createObjectStore('userinfo',{autoIncrement: true}); } } }
Before we have added data that defines the key as autoincreament type, now You can search for a single piece of data based on the ID.
function findDbdata(indexDbName,value) { var openRequest = indexedDB.open(indexDbName); var db; openRequest.onerror = function(e) {//当创建数据库失败时候的回调 console.log("Database error: " + e.target.errorCode); }; openRequest.onsuccess = function(event) { console.log("Database created"); db = openRequest.result; //创建数据库成功时候,将结果给db,此时db就是当前数据库 var transaction = db.transaction("userinfo",'readwrite'); var objectStore = transaction.objectStore("userinfo"); //var cursor = objectStore.openCursor(); var request = objectStore.get(Number(1));//查找i=1的对象,这里使用Number将1转换成数值类型 request.onsuccess = function(e) { var res = e.target.result; //查找成功时候返回的结果对象 console.dir(res); if (res) { for (var field in res) { //遍历每一个对象属性 console.log(field+":"+res[field]); // alert(res[field]); }; }; } }; openRequest.onupgradeneeded = function (event) {//更改数据库,或者存储对象时候在这里处理 }; }
function findAllDbdata(indexDbName) { var openRequest = indexedDB.open(indexDbName); var db; openRequest.onsuccess = function(event) { console.log("Database created"); db = openRequest.result; //创建数据库成功时候,将结果给db,此时db就是当前数据库 var transaction = db.transaction("userinfo",'readonly'); var objectStore = transaction.objectStore("userinfo"); var cursor = objectStore.openCursor(); cursor.onsuccess = function(e) { var res = e.target.result; if(res) { console.log("Key", res.key); var request = objectStore.get(Number(res.key));//根据查找出来的id,再次逐个查找 request.onsuccess = function(e) { var res = e.target.result; //查找成功时候返回的结果对象 //console.dir(res); if (res) { for (var field in res) { //遍历每一个对象属性 console.log(field+":"+res[field]); // alert(res[field]); }; }; } res.continue(); } } }; }
Delete followed by New is the same, you need to create a transaction, and then call the delete interface delete to delete the data
function deleteDataById(indexDbName) { var openRequest = indexedDB.open(indexDbName); var db; openRequest.onsuccess = function(event) { db = openRequest.result; //创建数据库成功时候,将结果给db,此时db就是当前数据库 var transaction = db.transaction("userinfo",'readwrite'); var objectStore = transaction.objectStore("userinfo"); var request = objectStore.delete(Number(2));//根据查找出来的id,再次逐个查找 request.onsuccess = function(e) { console.log("delete success"); } } }
Delete all through objectstore.clear() data.
function deleteAllData(indexDbName) { var openRequest = indexedDB.open(indexDbName); var db; openRequest.onsuccess = function(event) { db = openRequest.result; //创建数据库成功时候,将结果给db,此时db就是当前数据库 var transaction = db.transaction("userinfo",'readwrite'); var objectStore = transaction.objectStore("userinfo"); objectStore.clear(); } }
We can specify the index when creating the object store and use createIndex of the object store to create the index. The method has three parameters
Index name
Index attribute field name
索引属性值是否唯一
这里我新创建一个数据库,并且设置基于name和age的索引:
//指定主键自动增长 function insertAutoInc(indexDbName) { var userinfos=[{ id:1001, name:"小李", age:24 },{ id:1002, name:"老王", age:30 },{ id:1003, name:"王麻子", age:26 }]; var openRequest = indexedDB.open(indexDbName,2); openRequest.onerror = function(e) {//当创建数据库失败时候的回调 console.log("Database error: " + e.target.errorCode); }; openRequest.onsuccess = function(event) { console.log("Database created"); db = openRequest.result; //创建数据库成功时候,将结果给db,此时db就是当前数据库 //alert("this is :"+db); //打开和userinfo相关的objectstore的事物 var transaction = db.transaction("userinfo",'readwrite'); var store=transaction.objectStore("userinfo"); for(var i=0;i<userinfos.length;i++){ //alert("add"+userinfos[i]); store.add(userinfos[i]);//将对象添加至userinfo相关的objectstore中 } }; openRequest.onupgradeneeded = function(event) { var db = event.target.result; //在第一次创建数据库的时候,就创建userinfo相关的objectstore,以供后面添加数据时候使用 if(!db.objectStoreNames.contains('userinfo')){ //keyPath:Javascript对象,对象必须有一属性作为键值 var objectStore = db.createObjectStore('userinfo',{autoIncrement: true}); objectStore.createIndex('nameIndex','name',{unique:true});//这里假定名字不能重复,创建基于name的唯一索引 objectStore.createIndex('ageIndex','age',{unique:false});//创建基于age的索引 } } }
可以利用索引快速获取数据,name的索引是唯一的没问题,但是对于age索引只会取到第一个匹配值,要想得到所有age符合条件的值就需要使用游标了
function getDataByIndex(indexDbName) { var openRequest = indexedDB.open(indexDbName); var db; openRequest.onerror = function(e) {//当创建数据库失败时候的回调 console.log("Database error: " + e.target.errorCode); }; openRequest.onsuccess = function(event) { console.log("Database created"); db = openRequest.result; //创建数据库成功时候,将结果给db,此时db就是当前数据库 var transaction = db.transaction("userinfo",'readwrite'); var objectStore = transaction.objectStore("userinfo"); var nameIndex = objectStore.index("nameIndex"); //获得nameIndex索引 nameIndex.get("小李").onsuccess = function(e) { //根据name索引获得数据成功的回调 var userinfo = e.target.result; console.log("id:"+userinfo.id+"==name:"+userinfo.name+"==age:"+userinfo.age); } } }
刚才我们不仅创建了一个name的唯一索引,而且还创建了一个age的索引,如果我们根据age来获取数据,有可能会有多条,由于age不唯一,所以这个时候就需要使用游标来遍历数据。这里我先插入两条age=24的记录。
function getDataByAgeIndex(indexDbName) { var openRequest = indexedDB.open(indexDbName); var db; openRequest.onerror = function(e) {//当创建数据库失败时候的回调 console.log("Database error: " + e.target.errorCode); }; openRequest.onsuccess = function(event) { console.log("Database created"); db = openRequest.result; //创建数据库成功时候,将结果给db,此时db就是当前数据库 var transaction = db.transaction("userinfo",'readwrite'); var objectStore = transaction.objectStore("userinfo"); var nameIndex = objectStore.index("ageIndex"); //获得ageIndex索引 var request = nameIndex.openCursor();//openCursor没有参数的时候,表示获得所有数据 request.onsuccess = function(e) {//openCursor成功的时候回调该方法 var cursor = e.target.result; if (cursor) {//循环遍历cursor var userinfo = cursor.value; //alert(userinfo.name); console.log("id:"+userinfo.id+"==name:"+userinfo.name+"==age:"+userinfo.age); cursor.continue(); }; } } }
同时可以在opencursor的时候传入key range,来限制范围。
IDBKeyRange.only(value):只获取指定数据
IDBKeyRange.lowerBound(value,isOpen):获取最小是value的数据,第二个参数用来指示是否排除value值本身,也就是数学中的是否是开区间
IDBKeyRange.upperBound(value,isOpen):和上面类似,用于获取最大值是value的数据
IDBKeyRange.bound(value1,value2,isOpen1,isOpen2):表示在value1和value2之间,是否包含value1和value2
这里为了演示方便,我先删除之前的数据库,重新插入更多的数据,现在所有数据如下:
IDBKeyRange.only(value)
这里只需要在上面opencursor的时候将该限制条件传入即可,其他代码将保持不变,如下:
var request = nameIndex.openCursor(IDBKeyRange.only(Number(24)));
这里只根据age索引查询age==24的所有数据。
IDBKeyRange.lowerBound(value,isOpen)
在使用IDBKeyRange.lowerBound(28,true)来获取年龄大于28的并且包含28岁的所有数据。
var request = nameIndex.openCursor(IDBKeyRange.lowerBound(Number(28),true));
ok,今天就到这里了,希望大家喜欢。
The above is the detailed content of Sharing code examples of using indexdb in html5 (pictures and text). For more information, please follow other related articles on the PHP Chinese website!