美好的一天, 我不确定我的问题是否可能,这就是我问的原因:) 我正在开发一个在线时使用 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 数据库...这是我用来“尝试”填充 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请求。
如果您熟悉 promises,并且您也熟悉新的异步功能和 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();
关于javascript - 从 MySQL 到 IndexedDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44638999/