<!DOCTYPE html>
2 <head>
3 <meta charset="UTF-8">
4 <title>使用数据库实现Web留言本</title>
5 <script type="text/javascript">
6 //打开数据库
7 var datatable =
null;
8 var db = openDatabase(‘MyData‘, ‘‘, ‘My Database‘, 102400
);
9
10 //初始化
11 function init() {
12 datatable = document.getElementById("datatable"
);
13 showAllData();
14 }
15 //擦除表格中当前显示的数据
16 function removeAllData() {
17 for(
var i = datatable.childNodes.length - 1; i >= 0; i--
) {
18 datatable.removeChild(datatable.childNodes[i]);
19 }
20 var c = ""
;
21 c += "<tr>"
;
22 c += "<td>姓名</td>"
;
23 c += "<td>留言</td>"
;
24 c += "<td>留言时间</td>"
;
25 c += "</tr>"
;
26 datatable.innerHTML =
c;
27
28 }
29 //显示数据
30 function showData(row) {
31 var tr = document.createElement(‘tr‘
);
32 var t =
new Date();
33 t.setTime(row.time);
34
35 var c = ""
;
36 c += "<td>"+ row.name +"</td>"
;
37 c += "<td>"+ row.message +"</td>"
;
38 c += "<td>"+ t.toLocaleDateString() + " " + t.toLocaleTimeString(); +"</td>"
;
39
40 tr.innerHTML =
c
41
42 datatable.appendChild(tr);
43 }
44 //显示全部数据
45 function showAllData() {
46 //执行事务处理
47 db.transaction(
function(tx) {
48 //用回调函数来访问数据库
49 tx.executeSql(‘CREATE TABLE IF NOT EXISTS MsgData(name TEXT, message TEXT, time INTEGER)‘
, []);
50 tx.executeSql(‘SELECT * FROM MsgData‘, [],
function(tx, rs) {
51 removeAllData();
52 for(
var i = 0; i < rs.rows.length; i++
) {
53 showData(rs.rows.item(i));
54 }
55 });
56 });
57 }
58 //添加数据
59 function addData(name, message, time) {
60
61 db.transaction(
function(tx) {
62 tx.executeSql(‘INSERT INTO MsgData VALUES(?, ?, ?)‘, [name, message, time],
function(tx, rs) {
63 alert("成功保存数据!"
);
64 },
65 function(tx, error) {
66 alert(error.source + "::" +
error.message);
67 });
68 });
69 }
70 //保存数据
71 function saveData() {
72 var name = document.getElementById(‘name‘
).value;
73 var memo = document.getElementById(‘memo‘
).value;
74 var time =
new Date().getTime();
75 addData(name, memo, time);
76 showAllData();
77 }
78 </script>
79 </head>
80
81 <body onload="init();">
82 <h1>使用数据库实现Web留言本</h1>
83 <table>
84 <tr>
85 <td>姓名:</td>
86 <td><input type="text" id="name"></td>
87 </tr>
88 <tr>
89 <td>留言:</td>
90 <td><input type="text" id="memo"></td>
91 </tr>
92 <tr>
93 <td></td>
94 <td><input type="button" value="保存" onclick="saveData();"></td>
95 </tr>
96 </table>
97 <hr>
98 <table id="datatable" border="1"></table>
99 <p id="msg"></p>
100 </body>
101
102 </html>
View Code
html5本地存储(二)--- SQLList
标签:int var lis div str eal ddb source length