Phonegap CRUD操作 - window.openDatabase

时间:2018-04-02 15:03:33

标签: sqlite cordova phonegap

尝试使用phonegap / cordova创建CRUD操作,并且我一直接收"未捕获的DOMException:尝试突破用户代理的安全策略。在window.onload - 第17行和第34行;指向=>" db = window.openDatabase("员工"," 1.1"," LearnToProgram",200000);" 。这进一步影响db.transaction第25行“Uncaught TypeError:无法读取属性'事务'未定义的“,因为未创建数据库。我是否需要任何SQLLite插件,可能还有其他东西丢失了?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title>SQLLite DB App</title>
          <script type="text/javascript" src="cordova.js"></script>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
        <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
        <script>
        var db;

        window.onload=function()
        {
            document.getElementById('btnSave').addEventListener('click', saveData);
            db = window.openDatabase("employees",  "1.0", "LearnToProgram", 200000);
        }

        function saveData(e)
        {



            db.transaction(saveRecord, onSuccess, onError);
        }

        function saveRecord(transaction)
        {
            var name= document.getElementById('name').value;
            var email = document.getElementById('email').value;
            transaction.executeSql('CREATE TABLE IF NOT EXISTS employeesList (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Email TEXT NOT NULL) ');

            var sql= "INSERT INTO employeesList (Name,Email) VALUES ('" + name +"', '" + email + "')";
            console.log(sql);
            transaction.executeSql(sql);
        }

        function onSuccess()
        {
            console.log("Record Saved");
        }

        function onError(error)
        {
            console.log("SQL error: " + error.code);
        }
        </script>
    </head>
    <body>
        <div data-role="page">
        <div data-role="header"><h1>Database Storage</h1></div>
        <div data-role="main" class="ui-content">
        <label for="name">Name</label>
        <input type="text" id="name" />
        <label for="email">Email</label>
        <input type="text" id="email" />
        <button id="btnSave" type="submit">Save</button>
        <button id="showList">Show Employees</button>

        </div><!-- main-->
        </div><!-- page -->
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

也许我会帮助你。

打开数据库:

var db = null;

document.addEventListener('deviceready', function() {
  db = window.sqlitePlugin.openDatabase({
    name: 'my.db',
    location: 'default',
  });
});

重要提示:与其他Cordova / phonegap插件一样,您的应用程序必须等待deviceready事件。这在Angular / ngCordova / Ionic控制器/工厂/服务回调中尤其棘手,可能会在触发deviceready事件之前触发。