开发者

html5 Web SQL storage using different js files

开发者 https://www.devze.com 2023-02-10 06:12 出处:网络
I have a first.js which I open the database: $(function(开发者_如何学运维){ initDatabase(); });

I have a first.js which I open the database:

$(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;
    } 
}

Then, I want to execute sql statements from another file: second.js

function prueba_funcion () {
    DB.transaction(
        function (transaction) {
            transaction.executeSql("SELECT * FROM categorias;", [], nullDataHandler, errorHandler);
        }
    );
}

I receive this error: DB is not defined

In my HTML code I include first.js before second.js:

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

But I cant get it.


Your issue is caused by variable scope. If you want the variable DB to be global in scope, you have to instantize it outside of a function. Simply adding var DB = null; to first.js at the very top will probably solve your issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消