search
HomeWeb Front-endH5 TutorialMove the database from the server to the browser--indexedDB basic operation encapsulation

It is natural that the database belongs to the server, but sometimes the data may not need to be stored on the server, but the data is also recorded one by one. What should I do? Today I will lead you to experience a new feature of H5 - the charm of indexedDB. You can't help but sigh - incredible!

IndexedDB does not have the concept of creating a database. You can directly link to the database. If the database you link to does not exist, a database will be automatically created. Look at this example below.

 

nbsp;html><meta><title>Document</title><button>链接数据库</button><script>// 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&#39;T use "var indexedDB = ..." if you&#39;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&#39;t need window.mozIDB*)
   function connectDB(name,version,success,error){
         let dbConnect = indexedDB.open(name,version);
              dbConnect.onsuccess = function(e){
                  console.log(&#39;数据库链接成功!&#39;);
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log(&#39;数据库链接失败!&#39;);
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                success(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log(&#39;数据库更新成功,旧的版本号为:&#39;+oldVersion+",新的版本号为:"+newVersion);
            }
   }
   window.onload=function(){
           let btn  = document.getElementById(&#39;conbtn&#39;);
           btn.onclick = function(){
               connectDB(&#39;haha&#39;,1,function(){
                   console.log(&#39;链接成功,或者更新成功回调函数&#39;);
               },function(){
                   console.log(&#39;链接失败回调函数!&#39;)
               });
           }
   }</script>

I clicked twice to connect to the database, and the result is this.

We found one more thing in the indexedDB of Application.

 

 You can see that the haha ​​database has been successfully established.

The open method of indexedDB is used to link or update the database. The first creation is also considered an update. The first parameter is the name of the database, and the second parameter is the version number. The update event upgradeneeded is triggered when it is created for the first time or when the version number changes. The success event is triggered after the link is successful. The error event is triggered when the link fails.

2. Creating tables and indexes

 

nbsp;html><meta><title>Document</title><button>链接数据库</button><script>// 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&#39;T use "var indexedDB = ..." if you&#39;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&#39;t need window.mozIDB*)
   function connectDB(name,version,success,update,error){
         let dbConnect = indexedDB.open(name,version);
              dbConnect.onsuccess = function(e){
                  console.log(&#39;数据库链接成功!&#39;);
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log(&#39;数据库链接失败!&#39;);
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                update(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log(&#39;数据库更新成功,旧的版本号为:&#39;+oldVersion+",新的版本号为:"+newVersion);
            }
   }       function createTable(idb,storeName,key,idxs){if(!idb){
            console.log(idb);return ;
        }if(!key || !idxs){
            console.log(&#39;参数错误&#39;);return ;
        }if(!storeName){
            console.log(&#39;storeName必须&#39;);return ;
        }try{var store = idb.createObjectStore(storeName,key);
            console.log(&#39;数据库存储对象(table)创建成功&#39;);for(var i = 0;i<idxs.length;i++){var idx = idxs[i];
                store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters);
                    console.log(&#39;索引&#39;+idx.indexName+&#39;创建成功&#39;);
            }
        }catch(e){
            console.log(&#39;建表出现错误&#39;);
            console.log(JSON.stringify(e))
        }
    }
   window.onload=function(){
           let btn  = document.getElementById(&#39;conbtn&#39;);
           btn.onclick = function(){
               connectDB(&#39;haha&#39;,1,                 function(idb){
                   console.log(&#39;链接成功,或者更新成功回调函数&#39;);
               },function(idb){                   createTable(idb,&#39;test&#39;,{keyPath:&#39;id&#39;,autoIncrement:true},[
                       {
                       indexName:&#39;testIndex&#39;,
                     keyPath:&#39;name&#39;,
                     optionalParameters:{
                         unique:true,
                         multiEntry:false }}]);                   
               },function(){
                   console.log(&#39;链接失败回调函数!&#39;)
               });
           }
   }</script>

I clicked the button and the result was like this.

 

 

The two core methods used here are createObjectStore and createIndex. These two methods must be used in the event that the database is updated. implement.

The createObjectStore method can be understood as creating a table. It accepts the first parameter as a string, indicating the table name, and the second parameter is an object, specifying things related to the primary key, {keyPath: 'Which is the primary key? Field',autoIncrement: whether to auto-increment}.

The createIndex method creates an index and accepts three parameters. The first is a string indicating the name of the index, the second parameter indicates the field name (whose index), and the third parameter is an object. , check it yourself. The function of the index is to be used during query operations. If you don’t know the details, just google it yourself.

3. Add data

 

nbsp;html><meta><title>Document</title><button>链接数据库</button><button>添加数据</button><script>// 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&#39;T use "var indexedDB = ..." if you&#39;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&#39;t need window.mozIDB*)
   function connectDB(name,version,success,update,error){
         let dbConnect = indexedDB.open(name,version);
              dbConnect.onsuccess = function(e){
                  console.log(&#39;数据库链接成功!&#39;);
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log(&#39;数据库链接失败!&#39;);
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                update(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log(&#39;数据库更新成功,旧的版本号为:&#39;+oldVersion+",新的版本号为:"+newVersion);
            }
   }       function createTable(idb,storeName,key,idxs){if(!idb){
            console.log(idb);return ;
        }if(!key || !idxs){
            console.log(&#39;参数错误&#39;);return ;
        }if(!storeName){
            console.log(&#39;storeName必须&#39;);return ;
        }try{var store = idb.createObjectStore(storeName,key);
            console.log(&#39;数据库存储对象(table)创建成功&#39;);for(var i = 0;i<idxs.length;i++){var idx = idxs[i];
                store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters);
                    console.log(&#39;索引&#39;+idx.indexName+&#39;创建成功&#39;);
            }
        }catch(e){
            console.log(&#39;建表出现错误&#39;);
            console.log(JSON.stringify(e))
        }
    }function add(storeName,values){
    connectDB(&#39;haha&#39;,1,function(idb){var ts = idb.transaction(storeName,"readwrite");var store = ts.objectStore(storeName);        for(var i = 0;i<values.length;i++){
            (function(i){var value = values[i];var req = store.put(value);
                req.onsuccess = function(){
                    console.log("添加第"+i+"个数据成功");
                }
                req.onerror = function(e){
                    console.log("添加第"+i+"个数据失败");
                    console.log(JSON.stringify(e));
                }                            
            })(i)

        }
        ts.oncomplete = function(){
            console.log(&#39;添加数据事务结束!&#39;);
        }
    },function(){},function(){});

                
    }
   window.onload=function(){
           let btn  = document.getElementById(&#39;conbtn&#39;);
           btn.onclick = function(){
               connectDB(&#39;haha&#39;,1,                 function(idb){
                   console.log(&#39;链接成功,或者更新成功回调函数&#39;);
               },function(idb){
                   createTable(idb,&#39;test&#39;,{keyPath:&#39;id&#39;,autoIncrement:true},[
                       {
                       indexName:&#39;testIndex&#39;,
                     keyPath:&#39;name&#39;,
                     optionalParameters:{
                         unique:true,
                         multiEntry:false }}]);                   
               },function(){
                   console.log(&#39;链接失败回调函数!&#39;)
               });
           }
           let add1 = document.getElementById(&#39;add&#39;);
           add1.onclick = function(){
               add(&#39;test&#39;,[{name:"fjidfji",a:&#39;uuuu&#39;}])
           }
   }</script>

What’s amazing is that you don’t need to specify your fields when creating a table, and you can add them as you like when adding data. Adding data uses the put method of the table object. Previously, a transaction was required. Call a method from the transaction to get the storage object (which can be understood as a table). You will understand it by looking at the example.

4. Query data

Document链接数据库添加数据查询

Query operations mainly use cursors. There are many things to say about this, and I don’t have time to say it. , google by yourself. There are many more operations that I won’t go into here. Give me a simple library that I didn’t encapsulate very well, for reference only.

 A simple library.

(function(window){'use strict';
    window.dbUtil={
    indexedDB :(window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB),

    IDBTransaction :(window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction),

    IDBKeyRange :(window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange),

    IDBCursor : (window.IDBCursor || window.webkitIDBCursor || window.msIDBCursor),            
    idb:null,
    dbName:"",
    dbVersion:"",/**
     * 初始化数据库,创建表和建立链接
     * @param  {[type]} dbName    [description]
     * @param  {[type]} dbVersion [description]
     * @param  {[type]} storeObjs [description]
     * @return {[type]}           [description]     */initDB:function (dbName,dbVersion,storeObjs){this.dbName = dbName;this.dbVersion = dbVersion;var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion);var self = this;
        dbConnect.onsuccess = function(e){
            self.idb = e.target.result;
            self.log('数据库链接成功!');                
        }
        dbConnect.onerror = function(e){
            console.log(e)
            self.log('数据库链接失败!');
        }
        dbConnect.onupgradeneeded = function(e){
            self.idb = e.target.result;var ts = e.target.transaction;var oldVersion = e.oldVersion;var newVersion = e.newVersion;
            self.log('数据库更新成功,旧的版本号为:'+oldVersion+",新的版本号为:"+newVersion);if(storeObjs){for(var k = 0,len=storeObjs.length;k<len></len>

5. Advantages and disadvantages of using indexedDB

1. Advantages: You can put some data on the browser side, no need to By interacting with the server, you can implement some functions, reduce the burden on the server, and speed up the response.

 2. Disadvantages:

 (1) Unreliable: Users may delete indexedDB, and the data will be lost after changing browsers or devices.

 2) Inconvenient for data collection: Many times, data is saved to the server to obtain some data. If it is placed on the browser, these data are more difficult to obtain.

 (3) Unable to share: Different users cannot share data, and even different browsers on one device cannot share it.

Therefore, whether indexedDB is suitable requires weighing the pros and cons. It is not that with indexedDB, you just don’t care about anything and just put the data in.

 

The last two courses were designed and there were interviews. The article was written in a hurry. If there are any questions, please criticize and correct me. I'm looking for an internship recently. Dear friends, if what I write is good and the company is recruiting interns, you can give Daxiong a chance. Thank you!

The above is the detailed content of Move the database from the server to the browser--indexedDB basic operation encapsulation. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function