Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/450.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用不同js文件的html5 Web SQL存储_Javascript_Sql_Html_Storage - Fatal编程技术网

Javascript 使用不同js文件的html5 Web SQL存储

Javascript 使用不同js文件的html5 Web SQL存储,javascript,sql,html,storage,Javascript,Sql,Html,Storage,我有一个first.js打开数据库: $(function(){ initDatabase(); }); function initDatabase() { try { if (!window.openDatabase) { alert('Local Databases are not supported by your browser. Please use a Webkit browser for this demo');

我有一个first.js打开数据库:

$(function(){ 
    initDatabase();
});

function initDatabase() {

    try {
        if (!window.openDatabase) {
            alert('Local Databases are not supported by your browser. Please use a Webkit browser for this demo');
        } else {
            var shortName = 'MyDB';
            var version = '1.0';
            var displayName = 'First DB';
            var maxSize = 100000; // in bytes
            DB = openDatabase(shortName, version, displayName, maxSize);
            //dropTables();
            createTables();

        }
    } catch(e) {
        if (e == 2) {
            // Version mismatch.
            console.log("Invalid database version.");
        } else {
            console.log("Unknown error "+ e +".");
        }
        return;
    } 
}
然后,我想从另一个文件second.js执行sql语句

function prueba_funcion () {
    DB.transaction(
        function (transaction) {
            transaction.executeSql("SELECT * FROM categorias;", [], nullDataHandler, errorHandler);
        }
    );
}
我收到此错误:
DB未定义

在我的HTML代码中,我将first.js放在second.js之前:

<script type="text/javascript" src="js/first.js"></script>
<script type="text/javascript" src="js/second.js"></script>


但我无法理解。

您的问题是由可变范围引起的。如果希望变量
DB
在作用域中是全局变量,则必须在函数外部实例化它。只需添加
var DB=null到最上面的
first.js
可能会解决您的问题。

谢谢您的回复。我现在收到这个错误:无法调用null的方法'transaction',那么听起来您对函数
openDatabase
返回的任何内容都有其他问题。看起来你在用Firebug。。。调用
openDatabase
后,单击console.log(DB)并从那里开始。这必须是某个框架或库的一部分?它不是普通javascript的一部分。@Mateo,这是因为您在初始化数据库之前调用了它<代码>$(函数(){initDatabase();})将等待页面加载。你不需要等待。只需将initDatabase()放在first.js的末尾