我正在尝试将信息导出/下载到文件中。在我的浏览器中它工作正常,但只要我在我的phonegap应用程序中,它只是打开文件作为文本无法保存它,然后无法回到应用程序。 有什么建议?顺便说一句,我不是js专家 - 更像是新手!
function dbError(e) {
console.log("SQL ERROR");
console.dir(e);
}
function backup(table) {
var def = new $.Deferred();
curatio.webdb.db.readTransaction(function(tx) {
tx.executeSql("select * from "+table, [], function(tx,results) {
var data = convertResults(results);
console.dir(data);
def.resolve(data);
});
}, dbError);
return def;
}
$(document).on("click", "#doBackupBtn", function(e) {
e.preventDefault();
console.log("Begin backup process");
$.when(
backup("allergies")
).then(function(allergies, log) {
console.log("All done");
var data = {allergies:allergies}
var serializedData = JSON.stringify((data), null, 4);
console.log(serializedData);
download("Export.csv", serializedData);
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
});
});
function download(filename, content) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
pom.setAttribute('download', filename);
pom.click();
}
//Generic utility
function convertResults(resultset) {
var results = [];
for(var i=0,len=resultset.rows.length;i<len;i++) {
var row = resultset.rows.item(i);
var result = {};
for(var key in row) {
result[key] = row[key];
}
results.push(result);
}
return results;
}
</script>