再会,
我不确定我的问题是否可能,这就是我问的原因:)
我正在开发一个应用程序,它在线时使用 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 请求。
如果您熟悉 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)