[html5]使用localStorage兼容低版本Safari无法使用indexeddb的情况

本文探讨了如何在HTML5开发的应用中利用IndexedDB进行本地数据存储。对比localStorage,IndexedDB提供了更为灵活的数据管理和查询方式,尽管其兼容性稍逊一筹。文中还提供了一个示例,展示了IndexedDB的基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘要

简单场景描述:将html5开发的app内嵌入ios app中,有部分数据,需要在本地存储,就想到使用浏览器的localstorage或者indexeddb,另外localstorage存储的方式是key,value的方式,并且value是字符串类型的,一般会将json字符串的方式保存,但用起来不太方便,在使用的时候需要转换为json对象。indexeddb存储的是文档类型,类似于mongodb的document。操作更方便。但对低版本的兼容性不太好。

解决办法

http://git.oschina.net/wolfy/indexed-store-db

通过下面的代码判断当前浏览器是否支持indexed db

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;
    var db = {
        version: 1, // important: only use whole numbers!
        isSupport: function () {// support indexeddb or not
            if (!window.indexedDB)
                return false;
            return true;
        },
        ......
      }

一个例子

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="js/index-store-db-1.0.js"></script>
    <script>

        var user1 = { id: 1, name: "wolfy", age: 20 };
        var user2 = { id: 2, name: "wolfy", age: 20 };
        //set local indexed db name
        app.db.objectStoreName = "app_test";
        //save data to indexed db
        app.db.save(user1, function () {
            console.log("Save success");
        });
        app.db.save(user2, function () {
            console.log("Save success");
        });
        //query user by id
        app.db.get(1, function (item) {
            console.log("query success", item);
        });
        //query all user
        app.db.getAll(function (items) {
            console.log("query all success", items);
        });
        
        app.db.delete(1, function () {
            console.log("delete success");
        });
    </script>
</head>
<body>

</body>
</html>

结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值