在JavaScript函数中从SQL查询检索变量(重写)
我正在Apache Cordova中开发一个移动应用程序,它收集数据并将数据发送到web服务器。我想通过一个主函数来实现这一点 重写代码,使其更加集中和清晰在JavaScript函数中从SQL查询检索变量(重写),javascript,cordova,var,Javascript,Cordova,Var,我正在Apache Cordova中开发一个移动应用程序,它收集数据并将数据发送到web服务器。我想通过一个主函数来实现这一点 重写代码,使其更加集中和清晰 //main function launched by a button function sendData(){ //set all var as suggested var content = ''; var photoList = []; var fileName = ''; //call ch
//main function launched by a button
function sendData(){
//set all var as suggested
var content = '';
var photoList = [];
var fileName = '';
//call children functions
generateCsv(); // 1st child function
saveCSV(); // 2nd child function
uploadFile(); // 3rd child function
}
第一个函数从数据库中提取数据,并为上述var设置新值
function generateCsv() { // 1st child function
db.transaction(function(tx) {
tx.executeSql(selectAllStatement, [], function(tx, result) {
//do something I do not understand really... but work!
// but set value to var!!
console.log(content); //the new value is set correctly!!
});
});
}
现在,如果我尝试在主函数中的下一个函数中记录我的三个变量的值,我不会收到generateCsv函数所做的更改
function saveCSV() { // 2nd child function
console.log(fileName); //----not updated
console.log(content); //----not updated
console.log(photoList);//----not updated
//do something with my vars!
}
最后一个子函数将上载文件
function uploadFile(){ 3rd child function
//do something and upload....
}
代码是否已完成:
//------------------SEND DATA----------------->>
function sendData(){
var content = 'id,wateres,source,s_date,latitude,longitude,top,pump,pump_manual,other_pump,operator,operator_type,condition,disused,abandoned,access,water_presence,drinking_water,fee,fixme,note,photo,exif\n';
var fileName = '';
var date = new Date().toString();
var photoList = [];
generateCsv();
}
//---------------GENERATE CSV FILE--------------------->>
function generateCsv() {
db.transaction(function(tx) {
tx.executeSql(selectAllStatement, [], function(tx, result) {
dataset = result.rows;
if (dataset.length!=0){
for (var i = 0, item = null; i < dataset.length; i++) {
item = dataset.item(i);
//uploadPhoto(item['photo']);
photoList.push(item['photo']);
var exif = item['exif'].replace(/(\r\n|\n|\r)/gm, " | ");
exif = exif.replace(/,/g, '.');
content += item['id']+ ','
+ item['wateres'] + ','
+ item['source'] + ','
+ item['s_date'] + ','
+ item['lat'] + ','
+ item['lon'] + ','
+ item['top'] + ','
+ item['pump'] + ','
+ item['pump_manual'] + ','
+ item['other_pump'] + ','
+ item['operator'] + ','
+ item['operator_type'] + ','
+ item['condition'] + ','
+ item['disused'] + ','
+ item['abandoned'] + ','
+ item['access'] + ','
+ item['water_presence'] + ','
+ item['drinking_water'] + ','
+ item['fee'] + ','
+ item['fixme'] + ','
+ item['note'] + ','
+ item['photo'] + ','
+ exif + '\n';
fileName = item['source'] + '|' + date;
}
fileName = fileName.replace(/\ /g, "_");
fileName = fileName.replace(/\,/g, "");
fileName = fileName.replace(/\:/g, "-")+'.csv';
$('#message').html('<p><strong>Data have been collected.</strong> </p>');
saveCSV();
}
});
});
}
//--------------------------SAVE CSV ------------------
function saveCSV() {
console.log(fileName);
var fileObject;
document.addEventListener("deviceready", onDeviceReady, true);
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, onFileSystemSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(fileName, { create: true, exclusive: false },
gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileObject = fileEntry;
$('#saveFile_csv').on('click', function() {
saveFileContent();
//uploadFile(fileName);
});
}
function saveFileContent() {
fileObject.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
var myText = document.getElementById('my_text').value + content;
writer.write(myText);
writer.onwriteend = function(evt) {
$('#message').html('<p>File contents have been written.<br /><strong>File path:</strong> ' + fileObject.fullPath + '</p>');
var reader = new FileReader();
};
}
function fail(error) {
alert('fail to write file code = ' + error.code);
}
}
//----------------UPLOAD-CSV------------------------>>
function uploadFile(fileName) {
var fileURL = "///storage/emulated/0/Android/data/com.app/cache/"+fileName;
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
$('#contents').html('<strong>File uploaded</strong><br>'+ new Date() );
}
function fail(error) {
alert("An error has occurred uploading file: Code = " + error.code);
console.log("upload error source: " + error.source);
console.log("upload error target: " + error.target);
}
var uri = encodeURI("http://www.website.com/upload.php");
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType="text/plain";
var headers={'headerParam':'headerValue'};
options.headers = headers;
var ft = new FileTransfer();
ft.upload(fileURL, uri, win, fail, options);
$('#contents').html('<strong>Whait upload confirmation...</strong>');
}
/--------------发送数据---------------->>
函数sendData(){
var内容='id,水源,s_日期,纬度,经度,顶部,泵,泵手册,其他泵,操作员,操作员类型,条件,废弃,废弃,访问,水存在,饮用水,费用,修理费,注释,照片,出口';
var fileName='';
var date=新日期().toString();
var光表=[];
generateCsv();
}
//---------------生成CSV文件----------------->
函数generateCsv(){
数据库事务(功能(tx){
tx.executeSql(selectAllStatement,[],函数(tx,result){
数据集=result.rows;
如果(dataset.length!=0){
对于(var i=0,item=null;i已收集数据。');
saveCSV();
}
});
});
}
//--------------------------保存CSV------------------
函数saveCSV(){
log(文件名);
var文件对象;
文件。添加的监听器(“deviceready”,onDeviceReady,true);
函数ondevicerady(){
requestFileSystem(LocalFileSystem.TEMPORARY,0,onfileSystemsSuccess,fail);
}
函数onFileSystemsSuccess(文件系统){
getFile(文件名,{create:true,exclusive:false},
gotFileEntry,失败);
}
函数gotFileEntry(fileEntry){
fileObject=fileEntry;
$('saveFile_csv')。在('click',function()上{
saveFileContent();
//上传文件(文件名);
});
}
函数saveFileContent(){
createWriter(gotFileWriter,失败);
}
函数gotFileWriter(writer){
var myText=document.getElementById('my_text')。值+内容;
writer.write(myText);
writer.onwriteend=函数(evt){
$('#message').html('文件内容已写入。
文件路径:'+fileObject.fullPath+'');
var reader=new FileReader();
};
}
功能失败(错误){
警报(“写入文件代码失败=”+错误代码);
}
}
//----------------上传至CSV----------------->
函数上载文件(文件名){
var fileURL=“///storage/emulated/0/Android/data/com.app/cache/”+文件名;
函数win(r){
console.log(“Code=“+r.responseCode”);
console.log(“Response=“+r.Response”);
console.log(“Sent=“+r.bytesent”);
$('#contents').html('上传的文件
'+new Date());
}
功能失败(错误){
警报(“上传文件时出错:Code=“+error.Code”);
日志(“上传错误源:+error.source”);
log(“上传错误目标:+error.target”);
}
var uri=encodeURI(“http://www.website.com/upload.php");
var options=new FileUploadOptions();
options.fileKey=“file”;
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType=“text/plain”;
var headers={'headerParam':'headerValue'};
options.headers=标题;
var ft=新文件传输();
ft.upload(文件URL、uri、成功、失败、选项);
$('contents').html('what upload confirmation…);
}
谢谢 您只需设置函数之外的所有变量,如
var content = '';
var fileName = '';
var date = new Date().toString();
var photoList = [];
function getVarItem()
{
alert(content) //output: test string here or value here
}
然后,当你给变量赋值时,你必须使用这个全局变量
function getVarItem()
{
alert(content) //output: test string here or value here
}