IndexedDB - 使用 getAll() 函数
在前面的部分中,我们一次只从存储中检索一个对象。 现在我们可以检索对象存储的所有数据或子集。 get all 方法使用 getAll() 函数返回对象存储中的所有对象
语法
ObjectStore.getAll(optionalConstraint);
我们可以直接调用 getAll() 以返回对象存储中存储的所有对象,或者我们可以指定一个可选约束,例如来自汽车数据库的红色汽车
示例
在下面的示例脚本中,我们调用 getAll() 方法来一次返回对象存储中存储的所有对象 −
<!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <script> const request = indexedDB.open("botdatabase",1); request.onupgradeneeded = function(){ const db = request.result; const store = db.createObjectStore("bots",{ keyPath: "id"}); store.createIndex("branch_db",["branch"],{unique: false}); } request.onsuccess = function(){ document.write("database opened successfully"); const db = request.result; const transaction=db.transaction("bots","readwrite"); const store = transaction.objectStore("bots"); const branchIndex = store.index("branch_db"); store.add({id: 1, name: "jason",branch: "IT"}); store.add({id: 2, name: "praneeth",branch: "CSE"}); store.add({id: 3, name: "palli",branch: "EEE"}); store.add({id: 4, name: "abdul",branch: "IT"}); store.put({id: 4, name: "deevana",branch: "CSE"}); const query = branchIndex.getAll(["IT"]); query.onsuccess = function(){ document.write("query",query.result); } transaction.oncomplete = function(){ db.close; } } </script> </body> </html>
输出
database opened successfully query (1) [{...}] arg1:(1) [{...}] 0:{id: 1, name: 'jason', branch: 'IT'} length:1 [[Prototype]]:Array(0) [[Prototype]]:Object