从不同的页面/脚本打开现有的IndexedDB?

时间:2017-12-14 16:06:45

标签: javascript indexeddb

在我的列表页面上,我已成功创建了一个新的indexedDB实例,如下所示:

settings.js

$(document).ready(function () {

    if (!($('#route_instance'))) {
        //do nothing
    } else {
        saveRoomListOffline();
    }

    $('#all_routes li a').click(function(){
        $.jStorage.set('currentRoute', $(this).attr('rel'), { TTL: 28800000 }); 
    });
});


function saveRoomListOffline() {
    var rooms_array = [];
    $('#route_instance li').each(function () {
        var roomId = parseInt($(this).attr('id'), 10);
        var seqNo = parseInt($(this).attr('rel'), 10);
        var roomlink = $(this).find('a');
        var roomName = $(roomlink).html();
        var routeNumber = parseInt($('#rn').html());
        room_as_dict = {
            'room_id': roomId,
            'room_seq': seqNo,
            'room_name': roomName,
            'route_number' : routeNumber
        }
        rooms_array.push(room_as_dict);
    });

    //create idb
    var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;

    openRequest = window.indexedDB.open("rooms", 1);
    // Create the schema
    openRequest.onupgradeneeded = function() {
        var db = openRequest.result;
        var itemStore = db.createObjectStore("rooms", {keyPath: "room_id"});
        var index = itemStore.createIndex("RoomIndex", ["route_number", "room_seq"]);
    };

    openRequest.onerror = function(event) {
        console.error(event);
    };

    openRequest.onsuccess = function (event) {
        var db = openRequest.result;
        db.onerror = function(event) {
            // Generic error handler for all errors targeted at this database's requests
            console.error(event.target);
            window.alert("Database error: " + event.target.wePutrrorMessage || event.target.error.name || event.target.error || event.target.errorCode);
        };
        var transaction = db.transaction('rooms', "readwrite");
        var itemStore = transaction.objectStore("rooms");
        var index = itemStore.index("RoomIndex", ["route_number", "room_seq"]);
        putNext(rooms_array, itemStore);

        // Close the db when the transaction is done
        transaction.oncomplete = function() {
            db.close();
        };
    };
}

function putNext(rooms_array, itemStore) {
    for (i = 0; i < rooms_array.length; i++) { 
        itemStore.put(rooms_array[i]);
    } 
}

在下一页index.html上,我想检索使用上述脚本存储的数据,但它无效:

static-settings.js

function getRoomsInRoute() {
    var routeNumber = $.jStorage.get('currentRoute', '');
    // access all possible browser names for iDB
    var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
    var db = indexedDB.open('rooms', 1);
    var transaction = db.transaction([ 'rooms' ], 'readwrite');
    var store = transaction.objectStore('rooms');
    var index = store.index('route_number');
    var range = IDBKeyRange.only(routeNumber);
    var request = index.openCursor(range);
    request.onsuccess = function() {
    var cursor = this.result;
    if(cursor) {
        var room = cursor.value;
        $('#mylist').append("<li id="+ JSON.stringify(room.room_id) +" rel="+ JSON.stringify(room.room_seq) +"> " + JSON.stringify(room.room_name) + "</li> ");
        cursor.continue();
    } else {
        console.log('No rooms found or all rooms iterated');
    }
  };
  request.onblocked = function(event) {
        console.log("Error, cannot open database. Error message: Database in blocked state. " +
                "Please close all open windows, clear browser cache and use a fresh window.");
    };

    //Callback for error upon DB open
    request.onerror = function(event) {
      console.log('Error, cannot open database');
    };

    //Callback for success upon DB open
    request.onsuccess = function(event) {
        console.log('Success. ');
    };

    //Callback for onupgradeneeded upon DB open
    request.onupgradeneeded = function(event) {
        console.log('onupgradeneeded. Create/modify the database schema');
        this.dbHandler = e.target.result;
        this.dbHandler.createTable('rooms', {keyPath: 'room_id'});
    };
}

index.html

<script src="/js/lib/jquery-3.1.0.min.js"></script>
<!-- load the json2 library (required for jstorage use) -->
<script src="/js/lib/json2.js"></script>
<!-- load the jstorage library *-->
<script src="/js/lib/jstorage.js"></script>
<script src="/js/static-settings.js"></script>

列表页 - 与index.html相同,但不包括:

<script src="js/settings.js"></script>

我收到的错误消息是:

更新即可。新的错误消息(我已经删除了Dexie并完成了IndexedDB中的所有操作):

  

未捕获的TypeError:db.transaction不是函数   HTMLDocument中的getRoomsInRoute(static-settings.js:390)。   (静电settings.js:29)

     

at j(jquery-3.1.0.min.js:2)

     

at k(jquery-3.1.0.min.js:2)

1 个答案:

答案 0 :(得分:0)

在MozDev文档的帮助下:IDBCursorIDBKeyRange

<强> settings.js

function saveRoomListOffline() {
    var rooms_array = [];
    $('#route_instance li').each(function () {
        var roomId = parseInt($(this).attr('id'), 10);
        var seqNo = parseInt($(this).attr('rel'), 10);
        var roomlink = $(this).find('a');
        var roomName = $(roomlink).html();
        var routeNumber = parseInt($('#rn').html());
        room_as_dict = {
            'room_id': roomId,
            'room_seq': seqNo,
            'room_name': roomName,
            'route_number' : routeNumber
        }
        rooms_array.push(room_as_dict);
    });

    //create idb
    var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;

    openRequest = window.indexedDB.open("rooms", 1);
    // Create the schema
    openRequest.onupgradeneeded = function() {
        var db = openRequest.result;
        var itemStore = db.createObjectStore("rooms", {keyPath: "room_id"});
        var index = itemStore.createIndex("RoomIndex", ["route_number"]);
    };

    openRequest.onerror = function(event) {
        console.error(event);
    };

    openRequest.onsuccess = function (event) {
        var db = openRequest.result;
        db.onerror = function(event) {
            // Generic error handler for all errors targeted at this database's requests
            console.error(event.target);
            window.alert("Database error: " + event.target.error.name || event.target.error || event.target.errorCode);
        };
        var transaction = db.transaction('rooms', "readwrite");
        var itemStore = transaction.objectStore("rooms");
        var index = itemStore.index("RoomIndex", ["route_number"]);
        putNext(rooms_array, itemStore);

        // Close the db when the transaction is done
        transaction.oncomplete = function() {
            db.close();
        };
    };
}

<强> static-settings.js

function getRoomsInRoute() {
    var routeNumber = $.jStorage.get('currentRoute', '');
    var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;

    openRequest = window.indexedDB.open("rooms", 1);
    openRequest.onupgradeneeded = function() {
        var db = openRequest.result;
        var itemStore = db.createObjectStore("rooms", {keyPath: "room_id"});
        var index = itemStore.createIndex("RoomIndex", ["route_number"]);
    };

    openRequest.onerror = function(event) {
        console.error(event);
    };

    openRequest.onsuccess = function (event) {
        var db = openRequest.result;
        db.onerror = function(event) {
            // Generic error handler for all errors targeted at this database's requests
            console.error(event.target);
            console.log("Database error: " + event.target.error.name || event.target.error || event.target.errorCode);
        };
        var transaction = db.transaction(['rooms'], "readwrite");
        var itemStore = transaction.objectStore("rooms");
        var index = itemStore.index("RoomIndex", ["route_number"]);
        console.log('DB opened');

    var intRouteNumber = parseInt(routeNumber);

    itemStore.openCursor().onsuccess = function(event) {
        var cursor = event.target.result;
        if(cursor) {
            if(cursor.value.route_number == routeNumber) {
                $('#mylist').append("<li id="+ cursor.value.room_id +" rel="+ cursor.value.room_seq +"> " + '<small>'+ cursor.value.room_seq + '&nbsp;</small>' + cursor.value.room_name + "</li> ");
            }

            cursor.continue();
        } else {
            console.log('Entries all displayed.');
        }
    };

        // Close the db when the transaction is done
        transaction.oncomplete = function() {
            db.close();
        };
    };
}