Javascript:在脚本中声明全局变量并在另一个

时间:2016-10-05 11:51:34

标签: javascript html5 sql.js

我一直在尝试使用脚本创建与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];
}

}

&#34; checkbook.js&#34;文件在&#34; checks.html&#34;中调用文件是:

<!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");

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

1 个答案:

答案 0 :(得分: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作为另一个电话的回调