HTML5でindexdbを使用するコード例を共有する(画像とテキスト)
前に述べたように、html5 はオフライン アプリケーションを適切にサポートしており、クライアント上でキーと値のペアを保存するためのローカルストレージをサポートしています。また、マニフェスト ファイルを参照し、 キャッシュが必要なファイルを定義することもできます。 、実際、indexdb は index データベースとしても知られており、オフラインの オブジェクト を保存するために使用できます。始めましょう:
で try/catch を使用して、さらなる処理のために例外をキャッチすることもできます。 データベースを使用する
データベースが最初に作成されたとき、データベースは一度に 1 つのバージョンしか持つことができません。作成されたデータベースを変更する必要がある場合は、そのバージョン番号を変更する必要があります。バージョン番号を変更すると、 upgradeneeded コールバックがトリガーされるため、データベースまたはストレージ オブジェクトを変更するメソッドは upgradeneeded メソッドで実行する必要があります。
現在のブラウザがindexdbをサポートしているかどうかを確認する
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>
ログイン後にコピー 上記のコードは、クライアントに対してデータベースを作成できます。
<!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>
database deleteDatabase メソッドを呼び出し、削除する必要があるデータベースの名前を渡すことにより、既存のデータベースを削除します。
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); }; }
データの保存
objectstore
indexdb にはテーブルの概念はありませんが、オブジェクトストアは複数のタイプのデータを保存できる柔軟なデータ構造です。各レコードの指定されたフィールドをキー値 (keyPath) として使用することも、自動的に生成された増加する数値をキー値 (keyGenerator) として使用することもできますが、指定することはできません。選択キーの種類に応じて、objectStore に保存できるデータ構造も異なります。
Things
データベースのコンテンツを更新したり、新しいデータを挿入したりする場合、最初に Thing を開き、指定する必要があります。現在のものが操作されるオブジェクトストア。
読み取り専用: 読み取り、データベースデータを変更できません、同時に実行可能
読み取りおよび書き込み: readwrite、読み取りおよび書き込み操作を実行できます
バージョン変更: veri
onchange- 新しいデータの操作はトランザクションで実行する必要があり、トランザクションではオブジェクト ストアを指定する必要があるため、後で使用するためにデータベースを作成するときにのみオブジェクト ストアを初期化できます。
keyidを指定してデータを追加しますkeyidを指定することは、主キーを指定することとして理解できます
//添加数据 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"}); } } }
autoIncrementを指定することは、自動的に拡張する主キーを指定することとして理解できます。
//指定主键自动增长 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}); } } }
IDに基づいてデータを検索
キーを自動インクリームメントタイプとして定義するデータを追加する前に、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(); } } }; }

IDに基づいてデータを削除
DeleteはAdd
interface
deleteを呼び出す必要があります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"); } } }
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(); } }
- インデックス属性フィールド名
索引属性值是否唯一
这里我新创建一个数据库,并且设置基于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,今天就到这里了,希望大家喜欢。
以上がHTML5でindexdbを使用するコード例を共有する(画像とテキスト)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









HTML の表の境界線に関するガイド。ここでは、HTML でのテーブルの境界線の例を示しながら、テーブル境界線を定義する複数の方法について説明します。

これは、HTML でのネストされたテーブルのガイドです。ここでは、テーブル内にテーブルを作成する方法をそれぞれの例とともに説明します。

HTML マージン左のガイド。ここでは、HTML margin-left の概要とその例、およびそのコード実装について説明します。

HTML テーブル レイアウトのガイド。ここでは、HTML テーブル レイアウトの値と例および出力について詳しく説明します。

HTML 入力プレースホルダーのガイド。ここでは、コードと出力とともに HTML 入力プレースホルダーの例について説明します。

HTML でのテキストの移動に関するガイド。ここでは、概要、マーキー タグが構文でどのように機能するか、および実装例について説明します。

HTML オンクリック ボタンのガイド。ここでは、それらの紹介、動作、例、およびさまざまなイベントでの onclick イベントについてそれぞれ説明します。
