混合应用程序中的Web sql数据库

时间:2013-10-09 03:17:22

标签: html5 hybrid-mobile-app

我正在尝试使用web sql数据库在移动设备上显示数据。 下面是代码,我不知道如何在html页面体中显示数据库数据。

<!DOCTYPE html>
<html>
<head>
<title></title>

<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">

// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);

// Populate the database
//
function populateDB(tx) {
    tx.executeSql('DROP TABLE IF EXISTS DEMO');
    tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
    tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
    tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}

// Query the database
//
function queryDB(tx) {
    tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}

// Query the success callback
//
function querySuccess(tx, results) {
    var len = results.rows.length;
    console.log("DEMO table: " + len + " rows found.");
    for (var i=0; i<len; i++){
        console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data =  " + results.rows.item(i).data);
    }
}

// Transaction error callback
//
function errorCB(err) {
    console.log("Error processing SQL: "+err.code);
}

// Transaction success callback
//
function successCB() {
    var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
    db.transaction(queryDB, errorCB);
}

// device APIs are available
//
function onDeviceReady() {
    var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
    db.transaction(populateDB, errorCB, successCB);
}

</script>

       

示例DB

  

1 个答案:

答案 0 :(得分:0)

这是使用jquery(未测试)在表中显示它的一种方法。

<body>
    <table id="myTable"></table>
</body>

....
....

function querySuccess(tx, results) {
    // Get a reference to your table in the body tag
    var table  = $("#myTable");
    var len = results.rows.length;

    for (var i=0; i<len; i++){

        // Get the data from the database to be displayed
        var id = results.rows.item(i).id;
        var data = results.rows.item(i).data;

        // Create the html elements using jquery
        var tableRow = $('<tr/>', {});
        var tableId = $('<td/>', {text: id});
        var tableData = $('<td/>', {text: data});

        // Append the elements to the table
        tableRow.append(tableId);
        tableRow.append(tableData);
        table.append(tableRow);
    }
}