objectStore.add не добавляет данные с другим ключом в IndexedDb - PullRequest
0 голосов
/ 16 февраля 2019

Мне бы хотелось иметь кнопку, которая собирает значения из трех полей ввода, передает их в функцию javascript, которая, в свою очередь, превращает их в один объект и вводит их в объектный магазин базы данных IndexedDb.У меня есть его, чтобы ввести первые три значения как объект, но при последующих щелчках он передает их в функцию, но не добавляет их в базу данных.

function callIdb(entry1, entry2, entry3) {

    document.getElementById('registernewsletter').innerHTML = 'Check ' + entry1 + ' for New User Offer!';
    var nameI = entry1
    var ageI = entry2;
    var emailI = entry3;

    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction || {READ_WRITE: "readwrite"}; // This line should only be needed if it is needed to support the object's constants for older browsers
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;

    if (!window.indexedDB) {
        console.log("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.");
        } else { 
        console.log("You're good to go with IndexedDB");
        };

    var request = window.indexedDB.open("restaurantDatabase", 1);
    request.onerror = function(event) {
        console.log("Hi, YouFail.  PleaseTry again", event);
        };


    var restaurantData = [];
    var b = (function () {
      var c = [];
      return function () {
        c.push({name: nameI, age: ageI, email: emailI});
        return c;
        }
    })();

    var d = b();
    console.log(d);
    console.log("New data: ", d, d.isArray);
    d.forEach(function(rest) {
        console.log("I: ", d);
        });

    request.onupgradeneeded = function(event) {
        console.log('win upgrade');
        var db = event.target.result;
        console.log("OnUpgrade:  db= ", db);

        var oS = db.createObjectStore("restaurants", { keyPath: "email" });
        oS.createIndex("name", "name", { unique: false });
        oS.createIndex("email", "email", { unique: true });
        oS.createIndex("age", "age", { unique: false });

        oS.transaction.oncomplete = function(event) {
            var rTrans = db.transaction("restaurants", "readwrite").objectStore("restaurants");

            d.forEach(function(restaurant) {
                rTrans.add(restaurant);
                console.log("You followed directions! gd jb", restaurant, "stored in ", rTrans);
            });
        };
    };
    request.onupgradeneeded.onerror = function(event) {
        console.log("err", event);
    }
}

Должен ли я удалить дополнение изonupgradeneeded?Я думал, что все правки в БД должны быть внутри этого события.

    <form id="newsletter_form" class="newsletter_form">
        <input type="text" id="idbentry1" class="newsletter_input" placeholder="Restuarant Name" required="required">
        <input type="text" id="idbentry2" class="newsletter_input" placeholder="Years at Location">
        <input type="email" id="idbentry3" class="newsletter_input" placeholder="email">

Вставить значения в IndexedDb ()

Вот первая запись, действующая хорошо:

You're good to go with IndexedDB
rapidapp.js:198 [{…}]
rapidapp.js:199 New data:  [{…}] undefined
rapidapp.js:201 I:  [{…}]
rapidapp.js:212 win upgrade
rapidapp.js:214 OnUpgrade:  db=  IDBDatabase {name: "restaurantDatabase", version: 1, objectStoreNames: DOMStringList, onabort: null, onclose: null, …}
rapidapp.js:229 You followed directions! gd jb {name: "ert", age: "ww", email: "tt"} stored in  IDBObjectStore {name: "restaurants", keyPath: "email", indexNames: DOMStringList, transaction: IDBTransaction, autoIncrement: false}

И вот вторая запись останавливается до того, как будет обновлено.

You're good to go with IndexedDB
rapidapp.js:198 [{…}]
rapidapp.js:199 New data:  [{…}] undefined
rapidapp.js:201 I:  [{…}]

1 Ответ

0 голосов
/ 16 февраля 2019

Наконец получил:

function callIdb(entry1, entry2, entry3) {

    document.getElementById('registernewsletter').innerHTML = 'Check ' + entry1 + ' for New User Offer!';
    var nameI = entry1
    var ageI = entry2;
    var emailI = entry3;

    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction || {READ_WRITE: "readwrite"}; // This line should only be needed if it is needed to support the object's constants for older browsers
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;

    if (!window.indexedDB) {
        console.log("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.");
        } else { 
        console.log("You're good to go with IndexedDB");
        };

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

    var b = (function () {
      var c = [];
      return function () {
        c.push({name: nameI, age: ageI, email: emailI});
        return c;
        }
    })();

    request.onerror = function(event) {
        console.log("Hi, YouFail.  PleaseTry again", event);
        };

    var d = b();
    console.log(d);
    console.log("New data: ", d, d.isArray);
    d.forEach(function(rest) {
        console.log("I: ", d);
        });

    request.onupgradeneeded = function(event) {
        console.log('(WINR.UGN)Within request.upgradeneeded');

        var db = event.target.result;
        console.log("(WINR.UGN) db:", db);

        var oS = db.createObjectStore("restaurants", { keyPath: "email" });

        oS.createIndex("name", "name", { unique: false });
        oS.createIndex("email", "email", { unique: true });
        oS.createIndex("age", "age", { unique: false });  
        };

    request.onsuccess = function(event) {
        console.log('(WOR.NS) Within request.onsuccess');
        var db = event.target.result;
        console.log("(WOR.NS) db= ", db);

        var rTrans = db.transaction("restaurants", "readwrite").objectStore("restaurants"); 

        d.forEach(function(restaurant) {
            rTrans.add(restaurant);
            console.log("You followed directions! Well done. var restaurant: ", restaurant, "stored with this transaction: ", rTrans);
            });

        rTrans.oncomplete = function () {
            console.log("CONGRATULATIONS FOOLS.");
            }
        };

    request.onupgradeneeded.onerror = function(event) {
        console.log("err", event);
        }
    }
  1. Открыть базу данных вне всех обработчиков (пример запроса var).
  2. Объявить переменные (т.е. - пользовательский ввод и т. Д.) Снаружиобработчики.
  3. Обработчик request.onupgradeneeded с функцией создает objectStore и индексы, а затем эта функция выполняется, и обработчик ...
  4. request.onsuccess находится в игре.Здесь вы открываете транзакцию и добавляете данные.
  5. Используйте обработчики ошибок!

Кроме того, эта ссылка была наиболее полезной на данном этапе процесса: https://www.w3.org/TR/IndexedDB/#dom-idbtransactionmode-readwrite.

Спасибо, Пэр

...