openDatabase Hello World

时间:2010-03-25 22:20:48

标签: javascript jquery web-sql opendatabase

我正在尝试了解openDatabase,我想我已经将它转到INSERT INTO TABLE1,但我无法验证SELECT * FROM TABLE1是否正常工作。

<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1");
</script>
<script type="text/javascript">
var db;

$(function(){
    db = openDatabase('HelloWorld');

    db.transaction(
        function(transaction) {
            transaction.executeSql(
                'CREATE TABLE IF NOT EXISTS Table1 ' +
                '  (TableID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' +
                '   Field1 TEXT NOT NULL );'
            );
        }
    );

    db.transaction(
        function(transaction) {
            transaction.executeSql(
                'SELECT * FROM Table1;',function (transaction, result) {
                    for (var i=0; i < result.rows.length; i++) {
            alert('1');
                        $('body').append(result.rows.item(i));
                    }
                }, 
                errorHandler
            );
        }
    );

    $('form').submit(function() {
        var xxx = $('#xxx').val();
        db.transaction(
            function(transaction) {
                transaction.executeSql(
                'INSERT INTO Table1 (Field1) VALUES (?);', [xxx], function(){
                    alert('Saved!');
                }, 
                errorHandler
                );
            }
        );
        return false;
    });
});

function errorHandler(transaction, error) {
    alert('Oops. Error was '+error.message+' (Code '+error.code+')');
    transaction.executeSql('INSERT INTO errors (code, message) VALUES (?, ?);', 
    [error.code, error.message]);
    return false;
}
</script>
</head>
<body>
<form method="post">
    <input name="xxx" id="xxx" />
    <p>
    <input type="submit" name="OK" />
    </p>
    <a href="http://www.google.com">Cancel</a>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:6)

你几乎就在那里,只有两件事:

  1. 如果你想使用SQL语句回调,你应该向executeSql方法提供参数数组参数,即使你的查询不需要任何参数。
  2. 您应该在循环中显示一个字段,result.rows.item(i)是一个包含属性作为表字段的对象。
  3. 您的选择将如下所示:

    db.transaction(function(transaction) {
      transaction.executeSql('SELECT * FROM Table1',[], function (trx, result) {
        for (var i=0; i < result.rows.length; i++) {
          $('body').append(result.rows.item(i).Field1); // <-- getting Field1 value
        }
      }, errorHandler);
    });
    

    检查您的示例here