我刚开始使用indexedDB。
我能够在对象Store中写入数据,并在第一次点击它时获取数据。 当我试图再次点击时,我发现它可以将数据写入数据库,但似乎无法调用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");}
}
答案 0 :(得分:0)
我观察到将数据写入DB
就可以了
我只是复制/粘贴并测试了您的代码,第一次写入运行正常,但其他人没有(您可以使用浏览器调试工具查看indexeddb内容)。
原因: 您每次都设置相同的主键:
"id": 1
"id": 2
所以我无法解释为什么你的打开游标失败后(可能是因为你的对象存储请求进入错误状态?),但似乎是问题...