濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > 深入解析HTML5的IndexedDB索引數(shù)據(jù)庫(kù)

深入解析HTML5的IndexedDB索引數(shù)據(jù)庫(kù)

熱門(mén)標(biāo)簽:外呼線(xiàn)穩(wěn)定線(xiàn)路 pageadm實(shí)現(xiàn)地圖標(biāo)注 邢臺(tái)縣地圖標(biāo)注app 地圖標(biāo)注位置能賺錢(qián)嗎 外呼系統(tǒng)電話(huà)怎么投訴 南通數(shù)據(jù)外呼系統(tǒng)推廣 申請(qǐng)400電話(huà)流程簡(jiǎn)介 阜陽(yáng)企業(yè)外呼系統(tǒng) 呼和浩特外呼電銷(xiāo)系統(tǒng)排名

介紹
IndexedDB是HTML5 WEB數(shù)據(jù)庫(kù),允許HTML5 WEB應(yīng)用在用戶(hù)瀏覽器端存儲(chǔ)數(shù)據(jù)。對(duì)于應(yīng)用來(lái)說(shuō)IndexedDB非常強(qiáng)大、有用,可以在客戶(hù)端的chrome,IE,Firefox等WEB瀏覽器中存儲(chǔ)大量數(shù)據(jù),下面簡(jiǎn)單介紹一下IndexedDB的基本概念。
 
什么是IndexedDB
IndexedDB,HTML5新的數(shù)據(jù)存儲(chǔ),可以在客戶(hù)端存儲(chǔ)、操作數(shù)據(jù),可以使應(yīng)用加載地更快,更好地響應(yīng)。它不同于關(guān)系型數(shù)據(jù)庫(kù),擁有數(shù)據(jù)表、記錄。它影響著我們?cè)O(shè)計(jì)和創(chuàng)建應(yīng)用程序的方式。IndexedDB 創(chuàng)建有數(shù)據(jù)類(lèi)型和簡(jiǎn)單的JavaScript持久對(duì)象的object,每個(gè)object可以有索引,使其有效地查詢(xún)和遍歷整個(gè)集合。本文為您提供了如何在Web應(yīng)用程序中使用IndexedDB的真實(shí)例子。
 
開(kāi)始
我們需要在執(zhí)行前包含下面前置代碼

JavaScript Code復(fù)制內(nèi)容到剪貼板
  1. var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;   
  2.     
  3. //prefixes of window.IDB objects   
  4. var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;   
  5. var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange   
  6.     
  7. if (!indexedDB) {   
  8. alert("Your browser doesn't support a stable version of IndexedDB.")   
  9. }  

 
打開(kāi)IndexedDB
在創(chuàng)建數(shù)據(jù)庫(kù)之前,我們首先需要為數(shù)據(jù)庫(kù)創(chuàng)建數(shù)據(jù),假設(shè)我們有如下的用戶(hù)信息:

JavaScript Code復(fù)制內(nèi)容到剪貼板
  1. var userData = [   
  2. { id: "1", name: "Tapas", age: 33, email: "tapas@example.com" },   
  3. { id: "2", name: "Bidulata", age: 55, email: "bidu@home.com" }   
  4. ];  

現(xiàn)在我們需要用open()方法打開(kāi)我們的數(shù)據(jù)庫(kù):

JavaScript Code復(fù)制內(nèi)容到剪貼板
  1. var db;   
  2. var request = indexedDB.open("databaseName", 1);   
  3.     
  4. request.onerror = function(e) {   
  5. console.log("error: ", e);   
  6. };   
  7.     
  8. request.onsuccess = function(e) {   
  9. db = request.result;   
  10. console.log("success: "+ db);   
  11. };   
  12. request.onupgradeneeded = function(e) {   
  13.     
  14. }  

如上所示,我們已經(jīng)打開(kāi)了名為"databaseName",指定版本號(hào)的數(shù)據(jù)庫(kù),open()方法有兩個(gè)參數(shù):
1.第一個(gè)參數(shù)是數(shù)據(jù)庫(kù)名稱(chēng),它會(huì)檢測(cè)名稱(chēng)為"databaseName"的數(shù)據(jù)庫(kù)是否已經(jīng)存在,如果存在則打開(kāi)它,否則創(chuàng)建新的數(shù)據(jù)庫(kù)。
2.第二個(gè)參數(shù)是數(shù)據(jù)庫(kù)的版本,用于用戶(hù)更新數(shù)據(jù)庫(kù)結(jié)構(gòu)。
 
onSuccess處理
發(fā)生成功事件時(shí)“onSuccess”被觸發(fā),如果所有成功的請(qǐng)求都在此處理,我們可以通過(guò)賦值給db變量保存請(qǐng)求的結(jié)果供以后使用。
 
onerror的處理程序
發(fā)生錯(cuò)誤事件時(shí)“onerror”被觸發(fā),如果打開(kāi)數(shù)據(jù)庫(kù)的過(guò)程中失敗。
 
Onupgradeneeded處理程序
如果你想更新數(shù)據(jù)庫(kù)(創(chuàng)建,刪除或修改數(shù)據(jù)庫(kù)),那么你必須實(shí)現(xiàn)onupgradeneeded處理程序,使您可以在數(shù)據(jù)庫(kù)中做任何更改。 在“onupgradeneeded”處理程序中是可以改變數(shù)據(jù)庫(kù)的結(jié)構(gòu)的唯一地方。
 
創(chuàng)建和添加數(shù)據(jù)到表:
IndexedDB使用對(duì)象存儲(chǔ)來(lái)存儲(chǔ)數(shù)據(jù),而不是通過(guò)表。 每當(dāng)一個(gè)值存儲(chǔ)在對(duì)象存儲(chǔ)中,它與一個(gè)鍵相關(guān)聯(lián)。 它允許我們創(chuàng)建的任何對(duì)象存儲(chǔ)索引。 索引允許我們?cè)L問(wèn)存儲(chǔ)在對(duì)象存儲(chǔ)中的值。 下面的代碼顯示了如何創(chuàng)建對(duì)象存儲(chǔ)并插入預(yù)先準(zhǔn)備好的數(shù)據(jù):

JavaScript Code復(fù)制內(nèi)容到剪貼板
  1. request.onupgradeneeded = function(event) {   
  2. var objectStore = event.target.result.createObjectStore("users", {keyPath: "id"});   
  3. for (var i in userData) {   
  4. objectStore.add(userData[i]);    
  5. }   
  6. }  

我們使用createObjectStore()方法創(chuàng)建一個(gè)對(duì)象存儲(chǔ)。 此方法接受兩個(gè)參數(shù): - 存儲(chǔ)的名稱(chēng)和參數(shù)對(duì)象。 在這里,我們有一個(gè)名為"users"的對(duì)象存儲(chǔ),并定義了keyPath,這是對(duì)象唯一性的屬性。 在這里,我們使用“id”作為keyPath,這個(gè)值在對(duì)象存儲(chǔ)中是唯一的,我們必須確保該“ID”的屬性在對(duì)象存儲(chǔ)中的每個(gè)對(duì)象中存在。 一旦創(chuàng)建了對(duì)象存儲(chǔ),我們可以開(kāi)始使用for循環(huán)添加數(shù)據(jù)進(jìn)去。
 
手動(dòng)將數(shù)據(jù)添加到表:
我們可以手動(dòng)添加額外的數(shù)據(jù)到數(shù)據(jù)庫(kù)中。

JavaScript Code復(fù)制內(nèi)容到剪貼板
  1. function Add() {   
  2. var request = db.transaction(["users"], "readwrite").objectStore("users")   
  3. .add({ id: "3", name: "Gautam", age: 30, email: "gautam@store.org" });   
  4.     
  5. request.onsuccess = function(e) {   
  6. alert("Gautam has been added to the database.");   
  7. };   
  8.     
  9. request.onerror = function(e) {   
  10. alert("Unable to add the information.");    
  11. }   
  12.     
  13. }  

之前我們?cè)跀?shù)據(jù)庫(kù)中做任何的CRUD操作(讀,寫(xiě),修改),必須使用事務(wù)。 該transaction()方法是用來(lái)指定我們想要進(jìn)行事務(wù)處理的對(duì)象存儲(chǔ)。 transaction()方法接受3個(gè)參數(shù)(第二個(gè)和第三個(gè)是可選的)。 第一個(gè)是我們要處理的對(duì)象存儲(chǔ)的列表,第二個(gè)指定我們是否要只讀/讀寫(xiě),第三個(gè)是版本變化。
 
從表中讀取數(shù)據(jù)
get()方法用于從對(duì)象存儲(chǔ)中檢索數(shù)據(jù)。 我們之前已經(jīng)設(shè)置對(duì)象的id作為的keyPath,所以get()方法將查找具有相同id值的對(duì)象。 下面的代碼將返回我們命名為“Bidulata”的對(duì)象:

JavaScript Code復(fù)制內(nèi)容到剪貼板
  1. function Read() {   
  2. var objectStore = db.transaction(["users"]).objectStore("users");   
  3. var request = objectStore.get("2");   
  4. request.onerror = function(event) {   
  5. alert("Unable to retrieve data from database!");   
  6. };   
  7. request.onsuccess = function(event) {    
  8. if(request.result) {   
  9. alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);   
  10. } else {   
  11. alert("Bidulata couldn't be found in your database!");    
  12. }   
  13. };   
  14. }  

 
從表中讀取所有數(shù)據(jù)
下面的方法檢索表中的所有數(shù)據(jù)。 這里我們使用游標(biāo)來(lái)檢索對(duì)象存儲(chǔ)中的所有數(shù)據(jù):

JavaScript Code復(fù)制內(nèi)容到剪貼板
  1. function ReadAll() {   
  2. var objectStore = db.transaction("users").objectStore("users");    
  3. var req = objectStore.openCursor();   
  4. req.onsuccess = function(event) {   
  5. db.close();   
  6. var res = event.target.result;   
  7. if (res) {   
  8. alert("Key " + res.key + " is " + res.value.name + ", Age: " + res.value.age + ", Email: " + res.value.email);   
  9. res.continue();   
  10. }   
  11. };   
  12. req.onerror = function (e) {   
  13. console.log("Error Getting: ", e);   
  14. };    
  15. }  

該openCursor()用于遍歷數(shù)據(jù)庫(kù)中的多個(gè)記錄。 在continue()函數(shù)中繼續(xù)讀取下一條記錄。
刪除表中的記錄
下面的方法從對(duì)象中刪除記錄。

JavaScript Code復(fù)制內(nèi)容到剪貼板
  1. function Remove() {    
  2. var request = db.transaction(["users"], "readwrite").objectStore("users").delete("1");   
  3. request.onsuccess = function(event) {   
  4. alert("Tapas's entry has been removed from your database.");   
  5. };   
  6. }  

我們要將對(duì)象的keyPath作為參數(shù)傳遞給delete()方法。
 
最終代碼
下面的方法從對(duì)象源中刪除一條記錄:

JavaScript Code復(fù)制內(nèi)容到剪貼板
  1. <!DOCTYPE html>  
  2. <head>  
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  4. <title>IndexedDB</title>  
  5. <script type="text/javascript">  
  6. var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;   
  7.     
  8. //prefixes of window.IDB objects   
  9. var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;   
  10. var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange   
  11.     
  12. if (!indexedDB) {   
  13. alert("Your browser doesn't support a stable version of IndexedDB.")   
  14. }   
  15. var customerData = [   
  16. { id: "1", name: "Tapas", age: 33, email: "tapas@example.com" },   
  17. { id: "2", name: "Bidulata", age: 55, email: "bidu@home.com" }   
  18. ];   
  19. var db;   
  20. var request = indexedDB.open("newDatabase", 1);   
  21.     
  22. request.onerror = function(e) {   
  23. console.log("error: ", e);   
  24. };   
  25.     
  26. request.onsuccess = function(e) {   
  27. db = request.result;   
  28. console.log("success: "+ db);   
  29. };   
  30.     
  31. request.onupgradeneeded = function(event) {   
  32.     
  33. }   
  34. request.onupgradeneeded = function(event) {   
  35. var objectStore = event.target.result.createObjectStore("users", {keyPath: "id"});   
  36. for (var i in userData) {   
  37. objectStore.add(userData[i]);    
  38. }   
  39. }   
  40. function Add() {   
  41. var request = db.transaction(["users"], "readwrite")   
  42. .objectStore("users")   
  43. .add({ id: "3", name: "Gautam", age: 30, email: "gautam@store.org" });   
  44.     
  45. request.onsuccess = function(e) {   
  46. alert("Gautam has been added to the database.");   
  47. };   
  48.     
  49. request.onerror = function(e) {   
  50. alert("Unable to add the information.");    
  51. }   
  52.     
  53. }   
  54. function Read() {   
  55. var objectStore = db.transaction("users").objectStore("users");   
  56. var request = objectStore.get("2");   
  57. request.onerror = function(event) {   
  58. alert("Unable to retrieve data from database!");   
  59. };   
  60. request.onsuccess = function(event) {    
  61. if(request.result) {   
  62. alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);   
  63. } else {   
  64. alert("Bidulata couldn't be found in your database!");    
  65. }   
  66. };   
  67. }   
  68. function ReadAll() {   
  69. var objectStore = db.transaction("users").objectStore("users");    
  70. var req = objectStore.openCursor();   
  71. req.onsuccess = function(event) {   
  72. db.close();   
  73. var res = event.target.result;   
  74. if (res) {   
  75. alert("Key " + res.key + " is " + res.value.name + ", Age: " + res.value.age + ", Email: " + res.value.email);   
  76. res.continue();   
  77. }   
  78. };   
  79. req.onerror = function (e) {   
  80. console.log("Error Getting: ", e);   
  81. };    
  82. }   
  83. function Remove() {    
  84. var request = db.transaction(["users"], "readwrite").objectStore("users").delete("1");   
  85. request.onsuccess = function(event) {   
  86. alert("Tapas's entry has been removed from your database.");   
  87. };   
  88. }   
  89. </script>  
  90. </head>  
  91.     
  92. <body>  
  93. <button onclick="Add()">Add record</button>  
  94. <button onclick="Remove()">Delete record</button>  
  95. <button onclick="Read()">Retrieve single record</button>  
  96. <button onclick="ReadAll()">Retrieve all records</button>  
  97. </body>  
  98. </html>  

localStorage是不帶lock功能的。那么要實(shí)現(xiàn)前端的數(shù)據(jù)共享并且需要lock功能那就需要使用其它本儲(chǔ)存方式,比如indexedDB。indededDB使用的是事務(wù)處理的機(jī)制,那實(shí)際上就是lock功能。
  做這個(gè)測(cè)試需要先簡(jiǎn)單的封裝下indexedDB的操作,因?yàn)閕ndexedDB的連接比較麻煩,而且兩個(gè)測(cè)試頁(yè)面都需要用到

JavaScript Code復(fù)制內(nèi)容到剪貼板
  1. //db.js   
  2. //封裝事務(wù)操作   
  3. IDBDatabase.prototype.doTransaction=function(f){   
  4.   f(this.transaction(["Obj"],"readwrite").objectStore("Obj"));   
  5. };   
  6. //連接數(shù)據(jù)庫(kù),成功后調(diào)用main函數(shù)   
  7. (function(){   
  8.   //打開(kāi)數(shù)據(jù)庫(kù)   
  9.   var cn=indexedDB.open("TestDB",1);   
  10.   //創(chuàng)建數(shù)據(jù)對(duì)象   
  11.   cn.onupgradeneeded=function(e){   
  12.     e.target.result.createObjectStore("Obj");   
  13.   };   
  14.   //數(shù)據(jù)庫(kù)連接成功   
  15.   cn.onsuccess=function(e){   
  16.     main(e.target.result);   
  17.   };   
  18. })();   
  19.   接著是兩個(gè)測(cè)試頁(yè)面   
  20. <script src="db.js"></script>  
  21. <script>  
  22. //a.html   
  23. function main(e){   
  24.   (function callee(){   
  25.     //開(kāi)始一個(gè)事務(wù)   
  26.     e.doTransaction(function(e){   
  27.       e.put(1,"test"); //設(shè)置test的值為1   
  28.       e.put(2,"test"); //設(shè)置test的值為2   
  29.     });   
  30.     setTimeout(callee);   
  31.   })();   
  32. };   
  33. </script>  
  34. <script src="db.js"></script>  
  35. <script>  
  36. //b.html   
  37. function main(e){   
  38.   (function callee(){   
  39.     //開(kāi)始一個(gè)事務(wù)   
  40.     e.doTransaction(function(e){   
  41.       //獲取test的值   
  42.       e.get("test").onsuccess=function(e){   
  43.         console.log(e.target.result);   
  44.       };   
  45.     });   
  46.     setTimeout(callee);   
  47.   })();   
  48. };   
  49. </script>  

把localStorage換成了indexedDB事務(wù)處理。但是結(jié)果就不同

測(cè)試的時(shí)候b.html中可能不會(huì)立即有輸出,因?yàn)閕ndexedDB正忙著處理a.html東西,b.html事務(wù)丟在了事務(wù)丟隊(duì)列中等待。但是無(wú)論如何,輸出結(jié)果也不會(huì)是1這個(gè)值。因?yàn)閕ndexedDB的最小處理單位是事務(wù),而不是localStorage那樣以表達(dá)式為單位。這樣只要把lock和unlock之間需要處理的東西放入一個(gè)事務(wù)中即可實(shí)現(xiàn)。另外,瀏覽器對(duì)indexedDB的支持不如localStorage,所以使用時(shí)還得考慮瀏覽器兼容。

標(biāo)簽:楊凌 鶴崗 內(nèi)蒙古 黃山 撫順 辛集 德州 蚌埠

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《深入解析HTML5的IndexedDB索引數(shù)據(jù)庫(kù)》,本文關(guān)鍵詞  深入,解析,HTML5,的,IndexedDB,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《深入解析HTML5的IndexedDB索引數(shù)據(jù)庫(kù)》相關(guān)的同類(lèi)信息!
  • 本頁(yè)收集關(guān)于深入解析HTML5的IndexedDB索引數(shù)據(jù)庫(kù)的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    蒙城县| 沾化县| 阳西县| 昌吉市| 石嘴山市| 舟曲县| 滦南县| 宜宾市| 云和县| 永安市| 巫溪县| 沙湾县| 乳山市| 都匀市| 铜陵市| 腾冲县| 乌审旗| 南部县| 通许县| 沂水县| 紫阳县| 清徐县| 乐都县| 牡丹江市| 青浦区| 沂水县| 阳春市| 石渠县| 黔江区| 云梦县| 寿光市| 松阳县| 巴彦淖尔市| 准格尔旗| 泽普县| 资源县| 通辽市| 会东县| 普定县| 永仁县| 富蕴县|