Code example for indexedDB storage
This article brings you code examples about indexedDB storage. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>indexedDB(浏览器本地存储数据库)</title> </head> <body> <p>IndexedDB 就是浏览器提供的本地数据库,它可以被网页脚本创建和操作。</p> <p>IndexedDB 允许储存大量数据,提供查找接口,还能建立索引。</p> <h3>indexedDB特点</h3> <ol> <li>键值对存储:采用对象仓库存储数据,所有的数据类型都可以直接存入,主键是独一无二的</li> <li>异步:</li> <li>支持事务:IndexedDB 支持事务(transaction),这意味着一系列操作步骤之中,只要有一步失败,整个事务就都取消,数据库回滚到事务发生之前的状态,不存在只改写一部分数据的情况。</li> <li>同源限制: IndexedDB 受到同源限制,每一个数据库对应创建它的域名。网页只能访问自身域名下的数据库,而不能访问跨域的数据库。</li> </ol> <script> /** * databaseName:字符串,表示数据库的名字,不存在则新建 * version :第二个参数是整数,表示数据库的版本。默认为1 * 返回一个 IDBRequest 对象 对象通过三种事件error、success、upgradeneeded * * 新建数据库与打开数据库是同一个操作。如果指定的数据库不存在,就会新建。不同之处在于,后续的操作主要在upgradeneeded事件的监听函数里面完成 * * 新建数据步骤: * step1:新建对象仓库(即新建表 * step2:新建索引 * * */ //IDBDatabase对象 let db; //创建或者打开 let request = window.indexedDB.open('newIDB'); //删除数据库 var DBDeleteRequest = window.indexedDB.deleteDatabase('newIDB'); DBDeleteRequest.onerror = function (event) { console.log('Error'); }; DBDeleteRequest.onsuccess = function (event) { console.log('success'); }; //error事件--表示打开数据失败 request.onerror = function (event) { console.log('数据库打开报错'); db.close(); }; request.success = function (event) { //通过request对象的result属性拿到数据库对象 db = request.result; console.log(db); console.log('数据库打开成功') }; console.log(request); //onupgradeneeded---如果指定的版本号,大于数据库的实际版本号,就会发生数据库升级事件 request.onupgradeneeded = function (event) { //通过事件对象的target.result属性,拿到数据库实例。 console.log(event); //request对象的result属性上面,拿到一个IDBDatabase对象,它表示连接的数据库 db = event.target.result; let objectStore; // 更好的写发是判断表是否存在 if (!db.objectStoreNames.contains('newIDB')) { /**新建数据 * 新建对象仓库(即新建表) * 新增一张叫做person的表格,主键是id * */ //主键(key)是默认建立索引的属性。如果没有可以让 IndexedDB 自动生成主键db.createObjectStore('person',{ autoIncrement: true }) objectStore = db.createObjectStore('newIDB', {keyPath: 'id'}); /** * 新建索引 * 三个参数分别为索引名称、索引所在的属性、配置对象(说明该属性是否包含重复的值) * **/ objectStore.createIndex('name', 'name', {unique: false}); objectStore.createIndex('email', 'email', {unique: true}); } }; /**新增数据 * 新增数据指的是向对象仓库写入数据记录。这需要通过事务完成。 * 写入数据需要新建一个事务 * 新建时必须指定表格名称和操作模式("只读"或"读写") * 写入操作是一个异步操作,通过监听连接对象的success事件和error事件,了解是否写入成功。 * **/ function add() { //通过IDBTransaction.objectStore(name)方法,拿到 IDBObjectStore 对象,再通过表格对象的add()方法,向表格写入一条记录。 var request = db.transaction(['newIDB'], 'readwrite') .objectStore('newIDB') .add({id: 1, name: '张三', age: 24, email: 'zhangsan@example.com'}); request.onsuccess = function (event) { console.log('数据写入成功'); }; request.onerror = function (event) { console.log('数据写入失败'); } } setTimeout(function () { console.log(db); add(); }, 2000); /** 读取数据 * *读取数据也是通过事务完成。 * * * **/ function read() { //创建是务 let transaction = db.transaction(['newIDB']); //拿到 IDBObjectStore 对象 let objectStore = transaction.objectStore('newIDB'); //objectStore.get()方法用于读取数据,参数是主键的值。 let request = objectStore.get(1); //失败监听 request.onerror = function (event) { console.log('事务失败'); db.close() }; //成功监听 request.onsuccess = function (event) { if (request.result) { console.log('Name: ' + request.result.name); console.log('Age: ' + request.result.age); console.log('Email: ' + request.result.email); } else { console.log('未获得数据记录'); } }; } setTimeout(function () { read(); }, 4000); /**遍历数据 *遍历数据表格的所有记录,要使用指针对象 IDBCursor。 * * */ function readAll() { let objectStore = db.transaction('newIDB').objectStore('newIDB'); //新建指针对象的openCursor()方法是一个异步操作,所以要监听success事件。 objectStore.openCursor().onsuccess = function (event) { let cursor = event.target.result; if (cursor) { console.log('Id: ' + cursor.key); console.log('Name: ' + cursor.value.name); console.log('Age: ' + cursor.value.age); console.log('Email: ' + cursor.value.email); cursor.continue(); } else { console.log('没有更多数据了!'); } }; } setTimeout(function () { readAll(); }, 6000); /**跟新数据 *更新数据要使用IDBObject.put()方法。 * * */ function update() { //put()方法自动更新了主键为1的记录。 let request = db.transaction(['newIDB'], 'readwrite') .objectStore('newIDB') .put({id: 1, name: '李四', age: 35, email: 'lisi@example.com'}); request.onsuccess = function (event) { console.log('数据更新成功'); }; request.onerror = function (event) { console.log('数据更新失败'); db.close(); } } setTimeout(function () { update(); }, 8000); /**删除数据 *IDBObjectStore.delete()方法用于删除记录 * * **/ function remove() { let request = db.transaction(['newIDB'], 'readwrite') .objectStore('newIDB') .delete(1); request.onsuccess = function (event) { console.log('数据删除成功'); }; } // remove(); /**使用索引 * 索引的意义在于,可以让你搜索任意字段,也就是说从任意字段拿到数据记录。如果不建立索引,默认只能搜索主键(即从主键取值)。 * */ function search() { let request = db.transaction(['newIDB'], 'readonly') .objectStore('newIDB') .index('name') .get('李四'); request.onsuccess = function (e) { var result = e.target.result; if (result) { console.log('搜索成功') } else { console.log('搜索失败') } } } // search(); </script> </body> </html> **注意:使用的时候链接数据库,失败或者完成其他操作关闭数据库;**
This article has ended here. For more exciting content, you can pay attention to the JavaScript Video Tutorial column on the PHP Chinese website!
The above is the detailed content of Code example for indexedDB storage. 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





How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
