


Move 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!
1. Link to database
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.
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button type="" id='conbtn'>链接数据库</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'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*) function connectDB(name,version,success,error){ let dbConnect = indexedDB.open(name,version); dbConnect.onsuccess = function(e){ console.log('数据库链接成功!'); success(e.target.result); } dbConnect.onerror = function(e){ console.log('数据库链接失败!'); error(e); } dbConnect.onupgradeneeded = function(e){ success(e.target.result); let oldVersion = e.oldVersion; let newVersion = e.newVersion; console.log('数据库更新成功,旧的版本号为:'+oldVersion+",新的版本号为:"+newVersion); } } window.onload=function(){ let btn = document.getElementById('conbtn'); btn.onclick = function(){ connectDB('haha',1,function(){ console.log('链接成功,或者更新成功回调函数'); },function(){ console.log('链接失败回调函数!') }); } }</script></body></html>
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
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button type="" id='conbtn'>链接数据库</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'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*) function connectDB(name,version,success,update,error){ let dbConnect = indexedDB.open(name,version); dbConnect.onsuccess = function(e){ console.log('数据库链接成功!'); success(e.target.result); } dbConnect.onerror = function(e){ console.log('数据库链接失败!'); error(e); } dbConnect.onupgradeneeded = function(e){ update(e.target.result); let oldVersion = e.oldVersion; let newVersion = e.newVersion; console.log('数据库更新成功,旧的版本号为:'+oldVersion+",新的版本号为:"+newVersion); } } function createTable(idb,storeName,key,idxs){if(!idb){ console.log(idb);return ; }if(!key || !idxs){ console.log('参数错误');return ; }if(!storeName){ console.log('storeName必须');return ; }try{var store = idb.createObjectStore(storeName,key); console.log('数据库存储对象(table)创建成功');for(var i = 0;i<idxs.length;i++){var idx = idxs[i]; store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters); console.log('索引'+idx.indexName+'创建成功'); } }catch(e){ console.log('建表出现错误'); console.log(JSON.stringify(e)) } } window.onload=function(){ let btn = document.getElementById('conbtn'); btn.onclick = function(){ connectDB('haha',1, function(idb){ console.log('链接成功,或者更新成功回调函数'); },function(idb){ createTable(idb,'test',{keyPath:'id',autoIncrement:true},[ { indexName:'testIndex', keyPath:'name', optionalParameters:{ unique:true, multiEntry:false }}]); },function(){ console.log('链接失败回调函数!') }); } }</script></body></html>
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
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button type="" id='conbtn'>链接数据库</button><button type="" id='add'>添加数据</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'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*) function connectDB(name,version,success,update,error){ let dbConnect = indexedDB.open(name,version); dbConnect.onsuccess = function(e){ console.log('数据库链接成功!'); success(e.target.result); } dbConnect.onerror = function(e){ console.log('数据库链接失败!'); error(e); } dbConnect.onupgradeneeded = function(e){ update(e.target.result); let oldVersion = e.oldVersion; let newVersion = e.newVersion; console.log('数据库更新成功,旧的版本号为:'+oldVersion+",新的版本号为:"+newVersion); } } function createTable(idb,storeName,key,idxs){if(!idb){ console.log(idb);return ; }if(!key || !idxs){ console.log('参数错误');return ; }if(!storeName){ console.log('storeName必须');return ; }try{var store = idb.createObjectStore(storeName,key); console.log('数据库存储对象(table)创建成功');for(var i = 0;i<idxs.length;i++){var idx = idxs[i]; store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters); console.log('索引'+idx.indexName+'创建成功'); } }catch(e){ console.log('建表出现错误'); console.log(JSON.stringify(e)) } }function add(storeName,values){ connectDB('haha',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('添加数据事务结束!'); } },function(){},function(){}); } window.onload=function(){ let btn = document.getElementById('conbtn'); btn.onclick = function(){ connectDB('haha',1, function(idb){ console.log('链接成功,或者更新成功回调函数'); },function(idb){ createTable(idb,'test',{keyPath:'id',autoIncrement:true},[ { indexName:'testIndex', keyPath:'name', optionalParameters:{ unique:true, multiEntry:false }}]); },function(){ console.log('链接失败回调函数!') }); } let add1 = document.getElementById('add'); add1.onclick = function(){ add('test',[{name:"fjidfji",a:'uuuu'}]) } }</script></body></html>
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;k++){var storeObj = storeObjs[k];var storeName = storeObj.storeName;var key = storeObj.key;var idxs = storeObj.idxs; self.createTable(storeName,key,idxs) } } } },/** * 创建数据库存储对象(表) * @param {[type]} key [description] * @param {[type]} [description] * @return {[type]} [description] */createTable:function(storeName,key,idxs){var self = this;var idb = self.idb;if(!idb){ self.log('数据库没有链接');return ; }if(!key || !idxs){ self.log('参数错误');return ; }if(!storeName){ self.log('storeName必须');return ; }try{var store = idb.createObjectStore(storeName,key); self.log('数据库存储对象(table)创建成功');for(var i = 0;i<idxs.length;i++){var idx = idxs[i]; store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters); self.log('索引'+idx.indexName+'创建成功'); } }catch(e){ self.log('建表出现错误'); console.log(JSON.stringify(e)) } },/** * [add description] * @param {[type]} storeName [description] * @param {[type]} values [description] */add:function(storeName,values){var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion);var self = this; dbConnect.onsuccess = function(e){var idb = e.target.result;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(){ self.log("添加第"+i+"个数据成功"); } req.onerror = function(e){ self.log("添加第"+i+"个数据失败"); self.log(JSON.stringify(e)); } })(i) } ts.oncomplete = function(){ self.log('添加数据事务结束!'); } } },/** * [select description] * @param {[type]} storeName [description] * @param {[type]} count [description] * @param {Function} callback [description] * @param {[type]} indexName [description] * @return {[type]} [description] */select:function(storeName,count,callback,indexName){var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion);var self = this;var total = 0;var data = []; dbConnect.onsuccess = function(e){ self.log("数据库链接成功!");var idb = e.target.result;var ts = idb.transaction(storeName,"readonly");var store = ts.objectStore(storeName);var req = store.count();var req2 = null; req.onsuccess = function(){ total = this.result;var realCount = (count<=total)?count:total;if(typeof indexName == 'undefined'){var range = IDBKeyRange.bound(0,"9999999999999999999999"); req2 = store.openCursor(range,'prev');var cc = 0; req2.onsuccess = function(){var cursor = this.result;if(total == 0){ callback([]);return; }if(cursor){ cc++; data.push(cursor.value);if(cc==realCount){ callback(data);return; } cursor.continue(); } } req2.onerror = function(){ self.log("检索出错") } }else{//待写 } } } },/** * [delete description] * @param {[type]} storeName [description] * @param {[type]} key [description] * @return {[type]} [description] */delete:function(storeName,key,callback){var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion); let self = this; dbConnect.onsuccess = function(e){var idb = e.target.result;var ts = idb.transaction(storeName,'readwrite');var store = ts.objectStore(storeName); store.delete(key); self.log('删除成功!');if(callback){ callback(); } } },/** * [funciton description] * @param {[type]} storeName [description] * @param {[type]} key [description] * @param {[type]} existCall [description] * @param {[type]} notExistCall [description] * @return {[type]} [description] */isExist:function(storeName,key,existCall,notExistCall){var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion); dbConnect.onsuccess = function(e){var idb = e.target.result;var ts = idb.transaction(storeName,'readonly');var store = ts.objectStore(storeName);var req = store.get(key); req.onsuccess = function(){if(this.result == undefined){ notExistCall(); }else{ existCall(this.result); } } req.onerror = function(){ notExistCall(); } } },/** * clear * @param {[type]} storeName [description] * @return {[type]} [description] */clear:function clearObjectStore(storeName){var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion); dbConnect.onsuccess = function(e){var idb = e.target.result;var ts = idb.transaction(storeName,'readwrite');var store = ts.objectStore(storeName); store.clear(); } },/** * 删除数据库 * @param {[type]} dbName [description] * @return {[type]} [description] */dropDatabase:function(dbName){this.indexedDB.deleteDatabase(dbName);this.log('成功删除数据库:'+dbName); },/** * [log description] * @param {[type]} msg [description] * @return {[type]} [description] */log:function(msg){ console.log((new Date()).toTimeString()+":"+msg) } } })(window);
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

The Installation, Configuration and Optimization Guide for HDFS File System under CentOS System This article will guide you how to install, configure and optimize Hadoop Distributed File System (HDFS) on CentOS System. HDFS installation and configuration Java environment installation: First, make sure that the appropriate Java environment is installed. Edit /etc/profile file, add the following, and replace /usr/lib/java-1.8.0/jdk1.8.0_144 with your actual Java installation path: exportJAVA_HOME=/usr/lib/java-1.8.0/jdk1.8.0_144exportPATH=$J

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

In the process of developing a website, improving page loading has always been one of my top priorities. Once, I tried using the Miniify library to compress and merge CSS and JavaScript files in order to improve the performance of the website. However, I encountered many problems and challenges during use, which eventually made me realize that Miniify may no longer be the best choice. Below I will share my experience and how to install and use Minify through Composer.

There are many ways to monitor the status of HDFS (Hadoop Distributed File System) on CentOS systems. This article will introduce several commonly used methods to help you choose the most suitable solution. 1. Use Hadoop’s own WebUI, Hadoop’s own Web interface to provide cluster status monitoring function. Steps: Make sure the Hadoop cluster is up and running. Access the WebUI: Enter http://:50070 (Hadoop2.x) or http://:9870 (Hadoop3.x) in your browser. The default username and password are usually hdfs/hdfs. 2. Command line tool monitoring Hadoop provides a series of command line tools to facilitate monitoring
