【发布时间】:2014-05-28 05:06:45
【问题描述】:
我刚开始使用 indexedDB。
我能够在对象存储中写入数据并在第一次点击时获取数据。 当我尝试再次点击时,我观察到将数据写入 DB 可以正常工作,但似乎无法调用 OpenCursor.Success。
谁能指出差距?
这是我的代码..
function clickMe()
{
alert("Yes am inside the function..");
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
try {
var dbOpenRequest = window.indexedDB.open("MyDB");
alert("congretss I Opened The DB as well..");
dbOpenRequest.onsuccess = function(event){
try {
alert("I am inside the onsuccess Method");
var db = dbOpenRequest.result;
db.onerror=function(event){
};
var transaction = db.transaction(["My_ObjectStore"], "readwrite");
transaction.oncomplete = function(e){
};
transaction.onabort = function(e){
};
transaction.onerror = function(e){
};
try {
var objectStore = transaction.objectStore("My_ObjectStore");
alert("Wait am trying to write the data in DB..");
var objectId = new Date().getTime()
var data =([ {
"reference": "<a href='details.html'>DEV2014/557</a>",
"applicant": "Association",
"siteAddress": "631 Gregory Terrace, Bowen Hills",
"applicationType": "Decided Application",
"status": "Approved",
"action": "<a href='details.html' class='btn btn-primary'>View Details</a>",
"id": 1
},
{
"reference": "<a href='details.html'>DEV2014/557</a>",
"applicant": "Association",
"siteAddress": "631 Gregory Terrace, Bowen Hills",
"applicationType": "Decided Application",
"status": "Approved",
"action": "<a href='details.html' class='btn btn-primary'>View Details</a>",
"id": 2
}
]);
for(i in data)
{
var request = objectStore.add(data[i]);
}
alert("Writing data is finished.."+request);
//get all the data using cursor
objectStore.openCursor().onsuccess = function(event) {
alert("Now you can See the Data..");
var cursor = event.target.result;
if (cursor) {
alert(cursor.value.id);
cursor.continue();
}
else {
//alert("No more entries!");
}
};
}catch(e){alert("error while writting the data");}
}catch (e){
alert("An error occured when creating object store");
writeError(e);
}
};
dbOpenRequest.onupgradeneeded = function(event){
try{
var db = dbOpenRequest.result;
var transaction = dbOpenRequest.transaction;
var objectStore = db.createObjectStore("My_ObjectStore",{
"keyPath": "id",
"autoIncrement": true
});
}catch(e){alert("Error while crating object store");}
};
}
catch(e){alert("error");}
}
【问题讨论】:
-
为什么要在代码周围使用 try/catch 块?它不是必需的。你为什么把这个问题标记为jquery?这与jquery无关。你为什么要记录'congretss I Opened The DB as well..'而实际上你还没有打开数据库?你为什么要在不同的范围内反复定义对 onerror 的回调?为什么将同步 window.alert 与异步代码调用一起使用?为什么你半随机地使用分号来结束你的陈述?为什么要使用 for-in 来遍历数组?为什么你的代码无法阅读?
标签: javascript jquery indexeddb