0

我正在尝试使用 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>

示例数据库

4

1 回答 1

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);
    }
}
于 2013-10-18T21:34:13.357 回答