0

我一直在尝试使用脚本创建与 sqlite3 数据库的连接(主要思想来自 stackoverflow 答案),如下所示。在“checkbook.js”文件中,我有连接功能,在应该使用连接的功能下方,读取数据库并在表格中填写一些字段:

function connect_db(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'checks.db', true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(e) {
    var uInt8Array = new Uint8Array(this.response);
    db = new SQL.Database(uInt8Array);
    };
    xhr.send();
}

function fill_status(){
    var contents = window.db.exec("SELECT rowid,name FROM aux_status");
    values = contents[0].values;
    for (j=0;j<values.length;j++){
        var select = document.getElementById('status')
        var option = document.createElement('option');
        select.appendChild(option);
        option.value = values[0];
        option.innerHTML=values[1];
}

}

“checkbook.js”文件在“checks.html”文件中被调用,它是:

<!DOCTYPE html>
<html>
<head>
    <title>Checkbook v0.0.1</title>
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
    <link rel='icon' type='image/png' href='images/logo_ioniatex_bbg.png'>
    <link rel='stylesheet' type='text/css' href='css/general.css'>
    <script type='text/javascript' src='jscripts/general.js'></script>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' href='bootstrap-3.3.5-dist/css/bootstrap.min.css'>
    <script src='bootstrap-3.3.5-dist/jquery-1.12.0.min.js'></script>
    <script src='bootstrap-3.3.5-dist/js/bootstrap.min.js'></script>
    <script src="sql.js"></script>
    <script src="checkbook.js"></script>
</head>
<body>
...
<script>var db;connect_db();fill_status();</script>
</div>
</body>
</html>

但是当我打开文件(在 Firefox 中)时,我收到了来自 firebug 的消息

TypeError: window.db is undefined
var contents = window.db.exec("SELECT rowid,name FROM aux_status");

我想念什么?我尝试使用或不使用 db 变量声明var,甚至调用函数“fill_status”,window.db但我仍然得到相同的答案。我想connect_db在 html 文件的开头运行该函数,并在一些代码之后运行另一个使用全局db变量的代码,以免为我需要的每个数据提取调用与数据库的新连接。

4

1 回答 1

1

这段代码:

xhr.onload = function(e) {
  var uInt8Array = new Uint8Array(this.response);
  db = new SQL.Database(uInt8Array);
};

作为 onload 事件的回调运行。因此,由于后者的异步特性,在以下情况window.db下不进行初始化:

window.db.exec("SELECT rowid,name FROM aux_status");

被执行。

您应该调用fill_status另一个调用的回调

于 2016-10-05T11:56:26.597 回答