HTML5--Browser data cache--IndexedDB

Source: Internet
Author: User
Tags createindex

INDEXEDDB is a way for you to persist your data in the user's browser, providing a rich query function for your Web application, so that our application works both online and offline.

Because the IndexedDB itself is still evolving, the current implementation of IndexedDB is using a browser prefix. Browser vendors may have different implementations for standard IndexedDB APIs before the specification is more stable. But once a consensus is reached on the norm, the vendor will implement it without a prefix tag. In fact some implementations have removed browser prefixes: IE 10,firefox 16 and Chrome 24.

If you want to test your code in a browser that still uses the prefix, you can use the following code:

WINDOW.INDEXEDDB = WINDOW.INDEXEDDB | | WINDOW.MOZINDEXEDDB | | WINDOW.WEBKITINDEXEDDB | |  = window. IDbTransaction | | window.webkitidbtransaction | |  = window. Idbkeyrange | | Window.webkitidbkeyrange | | Window.msidbkeyrange

It is important to note that implementations that use prefixes may have problems, are not complete, or may be followed by older versions of the specification. Therefore, it is not recommended to use in a production environment. We are more inclined to explicitly not support a particular browser, rather than claiming support but actually running a problem:

function hasindexeddb () {   if (!  WINDOW.INDEXEDDB) {      returntrue;    }}

Open the database:

// Open Our database var request = Window.indexedDB.open ("MyTestDatabase");

INDEXEDDB Open the database method as above, must be request,indexeddb only one open method, the above code indicates that a "mytestdatabase" database is opened, the method can accept the second parameter:

// open Our database with a version number of 1 var request = Window.indexedDB.open ("MyTestDatabase", 1);

The second parameter's version number is an integer, and the currently open version number cannot be smaller than the existing version number, or it will be an error.

Almost all of the requests that we produce are the first thing to do when we are dealing with the addition of success and failure handler functions:

var db;
function (event) { // do something with request.errorcode! function(event) {
db = Event.target.result; // Do something with request.result!};

Request also has a fallback method:

function= event.target.result;   // Do something with request.result!};

The onupgradeneeded method is only executed if the version number is upgraded (if the current version number is 1, when we open the opening (StoreName, 2), onupgradeneeded executes).

Here's how the entire database operates:

When we create a new data table, we first create the table in the Onupgradeneeded method:

Only valid in the Onupgradeneeded method
var createobjectstore = function (db, storeName) { if (! Db.objectStoreNames.contains (StoreName)) { Db.createobjectstore (storeName, { ' id ') , true }) Console.log ("Createobjectstore:" + StoreName + ", success!) ") }}

To delete a table:

// Delete Store (called in onupgradeneeded) deleteobjectstore (db, StoreName) {    console.log (' Deleteobjectstore ')    if  ( Db.objectStoreNames.contains (StoreName)) {      Db.deleteobjectstore (storeName)      Console.log (" Deleteobjectstore: "+ StoreName +", success! ")    }}

Add data to the table:

varstudents: [{ID:1001, Name: "Byron", age:24}, {ID:1002, Name: "Frank", age:30}, {ID:1003, Name: "Aaron", age:26}, {ID:1004, Name: "Casper", age:26 }]//adding a data method to execute in onsuccessvarAddData =function(db, StoreName) {Console.log (' AddData Success ') Let transaction= Db.transaction (storeName, ' ReadWrite ')) Let store=Transaction.objectstore (storeName) Let request=NULL     for(Let i = 0; i < students.length; i++) {Request=Store.add (tstudents[i]) Request.onerror=function() {Console.error (' Database already has this data! ‘)} request.onsuccess=function() {Console.log (' Add success ')      }    }}

Note that when you execute the AddData method, make sure that the Createobjectstore method is executed, or you will get an error. After adding, the browser displays:

Query data:

  // query data (by keyword keyvalue)  var function (db, StoreName, keyValue) {    = db.transaction (storeName, ' readonly ')    =  Transaction.objectstore (storeName)    = store.get (keyValue)    function  (e) {      = e.target.result      console.log (Result)    }  }

Update data:

  // Update Data  var function (db, StoreName, keyValue) {    = db.transaction (storeName, ' ReadWrite ')    =  Transaction.objectstore (storeName)    = store.get (keyValue)    function  (e) {      = e.target.result      =      store.put (student)      Console.log (student)    }  }

Delete data:

  // Delete Data  var function (db, StoreName, keyValue) {    = db.transaction (storeName, ' ReadWrite ')    =  Transaction.objectstore (storeName)    = store. Delete (keyValue)     function () {      console.log (' delete succeeded ')    }    function  () {      Console.log ( ' delete failed ')    }  }

Clear the table:

  // Empty Store  var function (db, StoreName) {    = db.transaction (storeName, ' ReadWrite ')    = Transaction.objectstore (storeName)     = store.clear ()    function  () {      console.log (' empty success ')    }     function  () {      console.log (' empty failed ')    }  }

To close the database:

  // Close Database  var function (db) {    db.close ()    console.log (' off ')  }

To delete a database:

  // Delete Database  var function (db) {    console.log (' delete ')    window.indexedDB.deleteDatabase (db)  }

New table (with index):

  //New store--index (called in onupgradeneeded)  varCreateobjectstorewidthindex =function(db, storeName) {if(!db.objectStoreNames.contains (StoreName)) {Let store=Db.createobjectstore (StoreName, {keypath:' ID '}) Store.createindex (' Nameindex ', ' name ', {unique:true}) Store.createindex (' Ageindex ', ' age ', {unique:false}) Console.log ("Createobjectstore:" + StoreName + ", success! ")    }  }

After success the browser side displays:

Ways to get Data:

  //get Data (by index)  varGetdatabyindex =function(db, StoreName) {Let transaction= Db.transaction (StoreName, ' readonly ')) Let store=Transaction.objectstore (storeName) Let index= Store.index (' Nameindex ') Index.get (' Byron '). onsuccess =function(e) {Let student=e.target.result Console.log (Student)}} //using Cursors  varFetchstorebycursor =function(db, StoreName) {Let transaction=db.transaction (storeName) let store=Transaction.objectstore (storeName) Let request= Store.opencursor ()//Search AllRequest.onsuccess =function(e) {let cursor=E.target.resultif(cursor) {Let student=cursor.value Console.log (student) cursor.Continue()      }    }  }  //the index is combined with the cursor  varGetdatabymultiple =function(db, storeName) {//Specify cursor Range    //idbkeyrange.only (value): Gets only the specified data    //Idbkeyrange.lowerbound (Value,isopen): Gets data that is larger than value (Isopen:true does not contain value, False contains value)    //Idbkeyrange.upperbound (Value,isopen): Gets data that is smaller than value (Isopen:true does not contain value, False contains value)    //Idbkeyrange.bound (VALUE1,VALUE2,ISOPEN1,ISOPEN2)Let transaction =db.transaction (storeName) let store=Transaction.objectstore (storeName) Let index= Store.index (' Ageindex ') Index.opencursor (Idbkeyrange.bound (24, 30,true,true). onsuccess =function(e) {let cursor=E.target.resultif(cursor) {let S=Cursor.value Console.log (s) cursor.Continue()      }    }  }

If we need to update the version manually, we will first close the INDEXEDDB and then open the new version of the database:

  var function (DB, StoreName, version) {    CLOSEIDB (db)    Console.log (' updated version ', StoreName, version)      OPENIDB (StoreName, Version)  }

HTML5--Browser data cache--IndexedDB

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.