我正在Google Chrome中尝试WebSQL example。
有代码:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="lib/jquery.mobile-1.4.5.min.css" />
<script src="lib/jquery-1.9.0.min.js"></script>
<script src="lib/jquery.mobile-1.4.5.min.js"></script>
<script>
$( document ).ready(function() {
//add listener when device ready
var db = window.openDatabase("Dummy_DB", "1.0", "Just a Dummy DB", 200000); //will create database Dummy_DB or open it
//function will be called when device ready
db.transaction(populateDB, errorCB, successCB);
//create table and insert some record
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS SoccerPlayer (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Club TEXT NOT NULL)');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Alexandre Pato", "AC Milan")');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Van Persie", "Arsenal")');
}
//function will be called when an error occurred
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
//function will be called when process succeed
function successCB() {
console.log("success!");
db.transaction(queryDB,errorCB);
}
//select all from SoccerPlayer
function queryDB(tx){
tx.executeSql('SELECT * FROM SoccerPlayer',[],querySuccess,errorCB);
}
function querySuccess(tx,result){
var len = result.rows.length, i;
console.log("LEN=" + len)
for (i = 0; i < len; i++) {
console.log(result.rows.item(i)); // print ok: Object {id: 1, Name: "Alexandre Pato", Club: "AC Milan"} test.html:47 ....
}
$('#SoccerPlayerList').empty();
$.each(result.rows,function(index){
var row = result.rows.item(index); // Uncaught TypeError: Failed to execute 'item' on 'SQLResultSetRowList': The index provided is not a number. test.html:52(anonymous function) test.html:52st.extend.each jquery-1.9.0.min.js:1querySuccess test.html:51
// var row = result.rows.item(1); // it works good
$('#SoccerPlayerList').append('<li><a href="#"><h3 class="ui-li-heading">'+row['Name']+'</h3><p class="ui-li-desc">Club '+row['Club']+'</p></a></li>');
});
$('#SoccerPlayerList').listview();
}
});
</script>
</head>
<body>
<div data-role="page">
<div data-role="header" data-position="fixed" data-theme="b">
<h1>Soccer Player</h1>
</div>
<div data-role="content">
<ul id="SoccerPlayerList">
</ul>
</div>
</div>
<!--end of Soccer Player Page--->
</body>
</html>
如果我使用var row = result.rows.item(index);
,我会收到错误:Uncaught TypeError: Failed to execute 'item' on 'SQLResultSetRowList': The index provided is not a number.
但是如果我直接使用数字:var row = result.rows.item(1)
输出是好的(JS添加<li>
)。
Pure JavaScript for循环将所有对象打印到控制台。所以WebSQL的使用可能很好。
哪里出错?
答案 0 :(得分:1)
试试这个
for(index=0;index<results.rows.length;index++)
{
result.rows.item(index);
..........................
}