gogoend / blog

blogs, ideas, etc.
MIT License
9 stars 2 forks source link

IndexedDB 小实验 #60

Open gogoend opened 4 years ago

gogoend commented 4 years ago
let someData = [
    {
        "adcode": 110000,
        "children": [
            {
                "adcode": 110100,
                "name": "市辖区"
            }
        ],
        "name": "北京"
    },
    {
        "adcode": 120000,
        "children": [
            {
                "adcode": 120100,
                "name": "市辖区"
            }
        ],
        "name": "天津"
    },
    {
        "adcode": 130000,
        "children": [
            {
                "adcode": 130100,
                "name": "石家庄"
            },
            {
                "adcode": 130200,
                "name": "唐山"
            },
            {
                "adcode": 130300,
                "name": "秦皇岛"
            },
            {
                "adcode": 130400,
                "name": "邯郸"
            },
            {
                "adcode": 130500,
                "name": "邢台"
            },
            {
                "adcode": 130600,
                "name": "保定"
            },
            {
                "adcode": 130700,
                "name": "张家口"
            },
            {
                "adcode": 130800,
                "name": "承德"
            },
            {
                "adcode": 130900,
                "name": "沧州"
            },
            {
                "adcode": 131000,
                "name": "廊坊"
            },
            {
                "adcode": 131100,
                "name": "衡水"
            },
            {
                "adcode": 139000,
                "name": "省直辖"
            }
        ],
        "name": "河北"
    }
];
const dbName = "the_name";

var request = indexedDB.open(dbName, 2);

request.onerror = function(event) {
  // 错误处理
};
request.onupgradeneeded = function(event) {
  var db = event.target.result;

  var objectStore = db.createObjectStore("someData", { keyPath: "adcode" });

  objectStore.createIndex("adcode", "adcode", { unique: false });

  objectStore.createIndex("name", "name", { unique: true });

  // 使用事务的 oncomplete 事件确保在插入数据前对象仓库已经创建完毕
  objectStore.transaction.oncomplete = function(event) {
    // 将数据保存到新创建的对象仓库
    var someDataObjectStore = db.transaction("someData", "readwrite").objectStore("someData");
    someData.forEach(function(data) {
      someDataObjectStore.add(data);
    });
  };
};