gpt4 book ai didi

javascript - indexedDB 添加记录到 objectStore 只能工作一次

转载 作者:行者123 更新时间:2023-11-30 20:13:41 25 4
gpt4 key购买 nike

我试图了解 indexedDB 的工作原理并编写了一个相当基本的站点访问者跟踪器。这是第一次工作。第一次加载页面时,一切都按预期进行。我可以看到数据已添加到我的 objectStore 中。

现在每次刷新页面时,我都没有按预期添加另一条记录。我做错了什么?欢迎任何指导或帮助。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- The above 3 meta tags *must* come first in the head; any other
head content must come *after* these tags -->

<meta name="description" content="">
<meta name="author" content="">

<script language="JavaScript" src="http://www.geoplugin.net
/javascript.gp" type="text/javascript"></script>

</head>
<body>
// UI here
</body>
<script>
var timeDate = new Date();
var tD=timeDate.toString();
alert(timeDate);

var ip = geoplugin_request(); // get client ip
alert(ip);

var city = geoplugin_city(); // get client city
alert(city);

var country = geoplugin_countryName() ; // get client country
alert(country);

var os = navigator.oscpu; // get platform info
alert(os);

window.indexedDB = window.indexedDB || window.mozIndexedDB ||
window.webkitIndexedDB || window.msIndexedDB;

//prefixes of window.IDB objects
window.IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange ||
window.msIDBKeyRange

if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}

var visitorInfo = [{
date : tD,
ip : ip,
city : city,
country: country,
os :os },
];

var db;
var request = window.indexedDB.open("visitor", 1);

request.onerror = function(event) {
console.log("error: ");
};

request.onsuccess = function(event) {
db = request.result;
console.log("success: "+ db);
};

request.onupgradeneeded = function(event) {
var db = event.target.result;

if(!db.objectStoreNames.contains("userinfo")){
console.log("creating userinfo table..");
//var objectStore = db.createObjectStore("userinfo", {keyPath: "ip",autoIncrement:true});
var objectStore = db.createObjectStore("userinfo", {keyPath: "ip"});
}
else{
console.log("userinfo exists");
}

for (var i in visitorInfo) {
objectStore.add(visitorInfo[i]);
}
}

最佳答案

插入对象的代码位于 onupgradeneeded 处理程序中。 onupgradeneeded 处理函数仅在首次创建数据库或增加版本时运行。

另一方面,indexedDB.open 调用的成功处理程序每​​次都会在创建、升级或刚刚打开数据库时运行。

因此,您希望将插入对象的代码从 onupgradeneeded 处理程序移动到成功处理程序中。

关于javascript - indexedDB 添加记录到 objectStore 只能工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52137882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com