indexedDB

作者: 尘伽 | 来源:发表于2023-03-26 15:17 被阅读0次

    indexedDB存储数据

     使用IndexedDB API将数据存储在浏览器本地

    const request = indexedDB.open('myDatabase', 1)

    request.onerror = function(event) {

      console.log('Database error: ' + event.target.errorCode)

    }

    request.onupgradeneeded = function(event) {

      const db = event.target.result

      const objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id' })

      objectStore.createIndex('name', 'name', { unique: false })

    }

    request.onsuccess = function(event) {

      const db = event.target.result

      const transaction = db.transaction(['myObjectStore'], 'readwrite')

      const objectStore = transaction.objectStore('myObjectStore')

      const data = { id: 1, name: 'John Doe', age: 30 }

      const request = objectStore.add(data)

      request.onsuccess = function(event) {

        console.log('Data added to IndexedDB')

      }

      transaction.oncomplete = function(event) {

        db.close()

      }

    }

    indexedDB调用存储的数据

    调用先前存储在indexedDB的名称为myDAtabase的数据

    const request = indexedDB.open('myDatabase', 1)

    request.onerror = function(event) {

      console.log('Database error: ' + event.target.errorCode)

    }

    request.onsuccess = function(event) {

      const db = event.target.result

      const transaction = db.transaction(['myObjectStore'], 'readonly')

      const objectStore = transaction.objectStore('myObjectStore')

      const request = objectStore.getAll()

      request.onsuccess = function(event) {

        console.log(event.target.result)

      }

    }

    相关文章

      网友评论

          本文标题:indexedDB

          本文链接:https://www.haomeiwen.com/subject/bqiordtx.html