在 Web 應用程式中使用用戶端儲存的教學課程
建立現代 Web 應用程序,尤其是漸進式 Web 應用程式 (PWA) 時,擁有一種離線儲存資料的方法至關重要。 IndexedDB 是一個功能強大的客戶端資料庫,允許 Web 應用程式儲存和檢索數據,即使使用者處於離線狀態也是如此。本指南將引導您了解 IndexedDB 的基礎知識,向您展示如何在 Web 應用程式中建立、讀取、更新和刪除資料(CRUD 操作)。
什麼是 IndexedDB?
IndexedDB 是一個低階 API,用於客戶端儲存大量結構化資料(包括檔案和 blob)。與 localStorage 不同,IndexedDB 可讓您儲存複雜的資料類型,而不僅僅是字串。它使用非同步事務性資料庫模型,這使得它對需要處理大型資料集或離線資料同步的應用程式來說非常強大。
為什麼要使用 IndexedDB?
- 離線功能:非常適合漸進式網路應用程式 (PWA) 和離線優先應用程式。
- 儲存容量:與localStorage(限制在5-10MB左右)相比,IndexedDB可以儲存更多的資料。
- 靈活性:儲存複雜的對象,如陣列、對象,甚至 blob。
- 非同步:操作不會阻塞 UI 線程,這表示您的應用程式保持回應。
入門:設定 IndexedDB
讓我們深入了解使用 IndexedDB 的核心步驟。我們將涵蓋:
- 建立或開啟資料庫
- 建立物件儲存(表)
- 新增資料
- 讀取資料
- 更新資料
- 刪除資料
第 1 步:開啟資料庫
要與 IndexedDB 交互,首先需要開啟與資料庫的連線。如果資料庫不存在,則會建立它。
const request = indexedDB.open('MyCustomersDatabase', 1); request.onerror = (event) => { console.error('Database error:', event.target.errorCode); }; request.onsuccess = (event) => { const db = event.target.result; console.log('Database opened successfully', db); }; request.onupgradeneeded = (event) => { const db = event.target.result; if (!db.objectStoreNames.contains('customers')) { const objectStore = db.createObjectStore('customers', { keyPath: 'id' }); objectStore.createIndex('name', 'name', { unique: false }); objectStore.createIndex('email', 'email', { unique: true }); console.log('Object store created.'); } };
這是發生的事情:
- indexedDB.open 開啟或建立資料庫。
- onerror 處理開啟資料庫時的任何錯誤。
- onsuccess 在資料庫連線成功開啟時觸發。
- 當資料庫需要升級時(例如,如果這是第一次開啟資料庫或版本變更),則會觸發 onupgradeneeded。您可以在其中定義物件儲存(將它們視為 SQL 中的表)。
步驟2:向IndexedDB新增數據
現在我們已經設定了資料庫和物件存儲,讓我們在其中添加一些資料。
const addCustomer = (db, customer) => { const transaction = db.transaction(['customers'], 'readwrite'); const objectStore = transaction.objectStore('customers'); const request = objectStore.add(customer); request.onsuccess = () => { console.log('Customer added:', customer); }; request.onerror = (event) => { console.error('Error adding customer:', event.target.errorCode); }; } const customer = { id: 1, name: 'John Doe', email: 'john@example.com' }; request.onsuccess = (event) => { const db = event.target.result; addCustomer(db, customer); };
這是發生的事情:
- 我們建立一個具有「讀寫」存取權限的事務以允許修改。
- add() 方法用於將資料插入物件儲存中。
- 我們監聽成功和錯誤事件以確認資料是否新增成功。
步驟3:從IndexedDB讀取數據
從 IndexedDB 讀取資料也很簡單。讓我們使用 get() 方法來檢索剛剛新增的客戶。
const getCustomer = (db, id) => { const transaction = db.transaction(['customers'], 'readonly'); const objectStore = transaction.objectStore('customers'); const request = objectStore.get(id); request.onsuccess = (event) => { const customer = event.target.result; if (customer) { console.log('Customer found:', customer); } else { console.log('Customer not found.'); } }; request.onerror = (event) => { console.error('Error fetching customer:', event.target.errorCode); }; } request.onsuccess = (event) => { const db = event.target.result; getCustomer(db, 1); // Fetch customer with ID 1 };
步驟 4:更新 IndexedDB 中的數據
要更新現有記錄,我們可以使用 put() 方法,該方法的工作方式與 add() 類似,但如果鍵已存在,則會取代記錄。
const updateCustomer = (db, customer) => { const transaction = db.transaction(['customers'], 'readwrite'); const objectStore = transaction.objectStore('customers'); const request = objectStore.put(customer); request.onsuccess = () => { console.log('Customer updated:', customer); }; request.onerror = (event) => { console.error('Error updating customer:', event.target.errorCode); }; } const updatedCustomer = { id: 1, name: 'Jane Doe', email: 'jane@example.com' }; request.onsuccess = (event) => { const db = event.target.result; updateCustomer(db, updatedCustomer); };
步驟5:從IndexedDB中刪除數據
最後,要刪除一筆記錄,請使用delete()方法。
const deleteCustomer = (db, id) => { const transaction = db.transaction(['customers'], 'readwrite'); const objectStore = transaction.objectStore('customers'); const request = objectStore.delete(id); request.onsuccess = () => { console.log('Customer deleted.'); }; request.onerror = (event) => { console.error('Error deleting customer:', event.target.errorCode); }; } request.onsuccess = (event) => { const db = event.target.result; deleteCustomer(db, 1); // Delete customer with ID 1 };
結論
IndexedDB 是一個強大的解決方案,用於處理客戶端資料存儲,尤其是在離線優先的 Web 應用程式中。透過遵循本指南,您已經學會如何:
- 開啟並建立資料庫
- 建立物件儲存
- 新增、讀取、更新和刪除資料
使用 IndexedDB,您可以建立更具彈性的 Web 應用程序,在本地儲存數據,即使沒有互聯網連接也可以工作。
參考:
MDN Web 文件 - IndexedDB API
關於 IndexedDB 的工作原理、API 方法和用例的綜合指南。
MDN IndexedDB 指南Google 開發者 - IndexedDB
一篇詳細的文章,介紹了 IndexedDB 建立離線網路應用程式的最佳實踐和使用。
Google 開發者 - IndexedDBW3C 索引資料庫 API
W3C 的官方規格概述了 IndexedDB 的技術實現和結構。
W3C IndexedDB 規範
如果您希望在本教程之外探索有關 IndexedDB 的更多信息,這些資源將提供額外的深度和背景!
編碼愉快!
以上是IndexedDB 初學者指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

簡單JavaScript函數用於檢查日期是否有效。 function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //測試 var

本文探討如何使用 jQuery 獲取和設置 DOM 元素的內邊距和外邊距值,特別是元素外邊距和內邊距的具體位置。雖然可以使用 CSS 設置元素的內邊距和外邊距,但獲取準確的值可能會比較棘手。 // 設定 $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); 你可能會認為這段代碼很

本文探討了十個特殊的jQuery選項卡和手風琴。 選項卡和手風琴之間的關鍵區別在於其內容面板的顯示和隱藏方式。讓我們深入研究這十個示例。 相關文章:10個jQuery選項卡插件

發現十個傑出的jQuery插件,以提升您的網站的活力和視覺吸引力!這個精選的收藏品提供了不同的功能,從圖像動畫到交互式畫廊。讓我們探索這些強大的工具:相關文章:1

HTTP-Console是一個節點模塊,可為您提供用於執行HTTP命令的命令行接口。不管您是否針對Web服務器,Web Serv

本教程向您展示瞭如何將自定義的Google搜索API集成到您的博客或網站中,提供了比標準WordPress主題搜索功能更精緻的搜索體驗。 令人驚訝的是簡單!您將能夠將搜索限制為Y

當div內容超出容器元素區域時,以下jQuery代碼片段可用於添加滾動條。 (無演示,請直接複製到Firebug中) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

SublimeText3漢化版
中文版,非常好用

SublimeText3 Linux新版
SublimeText3 Linux最新版

記事本++7.3.1
好用且免費的程式碼編輯器

Dreamweaver CS6
視覺化網頁開發工具