从 MySQL 到 IndexedDB

from MySQL to IndexedDB

美好的一天, 我不确定我的问题是否可能,这就是我问的原因:) 我正在开发一个在线时使用 PHP/MySQL 的应用程序,但在离线时使用 indexedDB(好吧,这就是目标!)。 对于用户来说,它只是读取数据库(没有什么可写的)。 在线时,我想填充 indexedDB 数据库,以便能够在应用程序离线时使用 MySQL 数据库的内容立即使用它。

我想做的是这样的事情:

function checkNetwork() {
    if (!navigator.onLine) {
        console.log("Navigator is offline. Loading INDEXEDDB as is.");
        openIndexedDBDatabase();
    } else {
        console.log("Navigator is online. Loading database via PHP.");
        openPHPdatabase();
    }
}

我还没想好如何填充 IndexedDB 数据库...这是我用来 "try" 填充 openPHPdatabase() 函数的代码的摘录:

request.onsuccess = function (e) {

                    db = e.target.result;
                    var transaction = db.transaction("myDB", "readwrite");
                    var objectStore = transaction.objectStore("myDB");

                    console.log("Retrieve from PHP Database to indexedDB.");
                    $.getJSON('./php/database.php', function(data) {
                        $.each(data, function (key, value) {
                            //Populate here...
                        });
                    });
};

如果你有什么想法,我会感兴趣的! :) 提前致谢!

好吧,对于初学者来说,您将两个异步系统(ajax 和 indexedDB)混合在一起,这并不总是有效。为了保证一直有效,需要重写代码,先取json数据,等待完成,然后连接数据库,启动事务,执行put请求。

如果您熟悉 Promise,并且您也熟悉新的异步功能,并且 const/let,可能是这样的:

// Asynchronously open a connection to indexedDB
function openIndexedDBDatabase() {
 return new Promise(function(resolve, reject) {
   const request = indexedDB.open('dbname', dbversionnumber);
   request.onsuccess = () => resolve(request.result);
   request.onerror() = () => reject(request.error);
 });
}

// Asynchronously fetch some json data
function getJsonAsync(url) {
  return new Promise(function(resolve, reject) {
    $.getJSON(url, resolve);
  });
}

// Asynchronously store the data in indexedDB
function storeTheDataInIndexedDb(db, data) {
  return new Promise(function(resolve, reject) {
     const transaction = db.transaction('storename', 'readwrite');
     transaction.oncomplete = () => resolve();
     transaction.onerror = () => reject(transaction.error);
     const store = transaction.objectStore('storename');
     for(let obj of data) {
       store.put(obj);
     }
  });
}

// Asynchronously do all the things together
async function doStuff() {
   if(!navigator.onLine) {
      const data = await getJsonAsync('./php/database.php');
      const db = await openIndexedDBDatabase();
      await storeTheDataInIndexedDb(db, data);
      db.close();
   } else {
      openPHPdatabase();
   }
}

doStuff();