这似乎很简单,但出于某种原因无法正常工作
要求是
看起来很简单,但遇到onupgradeneeded的问题,即使在手动删除数据库之后也永远不会被调用
这是代码
<script type="text/javascript">
var id = GetItem();
if(id == null || id=="")
{
//based on some other logic
var GID = "test";
SetItem(GID);
}
function GetItem() {
var result = "";
try {
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
// Open the database
var open = indexedDB.open("DB", 1);
open.onupgradeneeded = function () {
var db = open.result;
var store = db.createObjectStore("Store", { keyPath: "id" });
};
open.onsuccess = function () {
// Start a new transaction
var db = open.result;
var transaction = db.transaction("Store", "readwrite");
var store = transaction.objectStore("Store");
var gid = store.get("GID");
result = kid.result.value;
};
transaction.oncomplete = function () {
db.close();
};
}
catch (err) {
console.error(err.message);
}
return result;
}
function SetItem(GID) {
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
// Open (or create) the database
var open = indexedDB.open("DB", 1);
var transaction = db.transaction(["Store"]);
var objectStore = transaction.objectStore("Store");
objectStore.put({ id: "GID", value: GID });
objectStore.onerror = function (event) {
console.error(err.message);
};
request.onsuccess = function (event) {
// Do something with the request.result!
alert(request.result.value);
};
transaction.oncomplete = function () {
db.close();
};
}
</script>
本地存储不是一种选择
答案 0 :(得分:1)
有一些小问题,但如果你绕过它们,你可以让你的代码工作。我们先来看看SetItem
:
var open = indexedDB.open("DB", 1);
这是一个异步调用 - 因此在您对打开的数据库执行某些操作之前,必须先将onsuccess
和onerror
附加到其中。稍后您将open
引用为db
,但如果它是正确的,它仍然会抛出错误,因为open
不会引用您的数据库。以下是我修复它的方法:
var open = indexedDB.open("DB", 1);
open.onerror = function(event) {
console.log("Error loading database");
}
open.onsuccess = function(event) {
var db = dbRequest.result;
var transaction = db.transaction("Store", "readwrite");
var objectStore = transaction.objectStore("Store");
objectStore.put({ id: "GID", value: GID });
/* ....... */
}
如您所见,我也将“readwrite”传递给db.transaction
。如果要将对象放入数据库,则必须执行此操作。
还有一些其他小问题 - kid
而不是gid
。我通过进入Chrome Dev Tools控制台(ctrl + shift + i)和读取错误修复了大部分问题 - 您还可以打开(Application - &gt; IndexedDB)并在运行代码之前删除它以确保实际发生的事情。请记住,每次进行异步调用并想要读取响应时,都需要在完成后读取它。您的代码中的另一个示例:
var gid = store.get("GID"); // here you make asynchronous call
result = kid.result.value; // here you're trying to get result immediately
它应该是这样的:
var gid = store.get("GID");
gid.onsuccess = function(event) { /* ... */ }