indexedDB将记录添加到objectStore仅工作一次

时间:2018-09-02 14:20:15

标签: javascript indexeddb

我试图了解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]);
        }
     }

1 个答案:

答案 0 :(得分:1)

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

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

因此,您想要将将对象从onupgradeneed处理程序插入到成功处理程序中的代码。