前言
本章主要內(nèi)容是Web Storage與本地?cái)?shù)據(jù)庫(kù),其中Web Storage 是對(duì)cookie的優(yōu)化,本地?cái)?shù)據(jù)庫(kù)是HTML5新增的一個(gè)功能,使用它可以在客戶(hù)端建立一個(gè)數(shù)據(jù)庫(kù)
大大減輕服務(wù)器端的負(fù)擔(dān),加快訪問(wèn)數(shù)據(jù)速度。
學(xué)習(xí)本章需要掌握Web Storage基本概念,了解sessionStorage與localStorage的使用與差別
掌握本地?cái)?shù)據(jù)庫(kù)的使用
什么是WebStorage?
前面說(shuō)過(guò),webstorage是對(duì)cookie的優(yōu)化而來(lái),HTML4中使用cookie在客戶(hù)端存儲(chǔ)用戶(hù)數(shù)據(jù),長(zhǎng)期使用發(fā)現(xiàn)存在以下問(wèn)題:
大小限制在4kbcookie每次隨HTTP事務(wù)一起發(fā)送,浪費(fèi)帶寬正確操作cookie很復(fù)雜(這個(gè)有待考慮)
由于以上問(wèn)題,HTML5提出WebStorage作為新的客戶(hù)端本地保存技術(shù)。
Web Storage 技術(shù)在web上存儲(chǔ)數(shù)據(jù)即針對(duì)客戶(hù)端本地;具體來(lái)說(shuō)分為兩種:
sessionStrage:
session即會(huì)話的意思,在這里的session是指用戶(hù)瀏覽某個(gè)網(wǎng)站時(shí),從進(jìn)入網(wǎng)站到關(guān)閉網(wǎng)站這個(gè)時(shí)間段,session對(duì)象的有效期就只有這么長(zhǎng)。</p>
<p>localStorage:
將數(shù)據(jù)保存在客戶(hù)端硬件設(shè)備上,不管它是什么,意思就是下次打開(kāi)計(jì)算機(jī)時(shí)候數(shù)據(jù)還在。</p>
<p>兩者區(qū)別就是一個(gè)作為臨時(shí)保存,一個(gè)擁有長(zhǎng)期保存。
使用示例
簡(jiǎn)單應(yīng)用
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<h1>
Web Storage 實(shí)驗(yàn)</h1>
<div id="msg" style=" margin: 10px 0; border: 1px solid black; padding: 10px; width: 300px; height: 100px;">
</div>
<input type="text" id="text" />
<select id="type">
<option value="session">sessionStorage</option>
<option value="local">localStorage</option>
</select>
<button onclick="save();">
保存數(shù)據(jù)</button>
<button onclick="load();">
讀取數(shù)據(jù)</button>
<script type="text/javascript">
var msg = document.getElementById('msg'),
text = document.getElementById('text'),
type = document.getElementById('type');
function save() {
var str = text.value;
var t = type.value;
if (t == 'session') {
sessionStorage.setItem('msg', str);
} else {
localStorage.setItem('msg', str);
}
}
function load() {
var t = type.value;
if (t == 'session') {
msg.innerHTML = sessionStorage.getItem('msg');
} else {
msg.innerHTML = localStorage.getItem('msg');
}
}
</script>
</body>
</html>
![](/d/20211016/290a5c3f2de368e885ce9e2a7683ab36.gif)
在chrome瀏覽器下看會(huì)有感覺(jué)的。
簡(jiǎn)單web留言板
簡(jiǎn)單留言板
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<h1>
Web Storage 實(shí)驗(yàn)</h1>
<div id="msg" style="margin: 10px 0; border: 1px solid black; padding: 10px; width: 300px;
min-height: 100px;">
</div>
<input type="text" id="text" />
<button onclick="save();">
留言</button>
<button onclick="_clear();">
清空</button>
<script type="text/javascript">
var msg = document.getElementById('msg'),
text = document.getElementById('text');
function save() {
var str = text.value;
var k = new Date().getTime();
localStorage.setItem(k, str);
init();
}
function init() {
msg.innerHTML = '';
var dom = '';
for (var i = 0, len = localStorage.length; i < len; i++) {
dom += '<div>' + localStorage.key(i) + ':' + localStorage.getItem(localStorage.key(i)) + '</div>'
}
msg.innerHTML = dom;
}
function _clear() {
msg.innerHTML = '';
localStorage.clear();
}
</script>
</body>
</html>
![](/d/20211016/95ec4aeb1ced0982b4322bb55336e6b1.gif)
更復(fù)雜的運(yùn)用中,可以將value值用作json字符串,以此達(dá)到用作數(shù)據(jù)表的目的;
本地?cái)?shù)據(jù)庫(kù)
在HTML5中內(nèi)置了一個(gè)可通過(guò)sql訪問(wèn)的數(shù)據(jù)庫(kù)(新瀏覽器果真強(qiáng)大?。。?,所以在HTML4中數(shù)據(jù)只能存在服務(wù)器端,HTML5則改變了這一原則。
這種不需要存儲(chǔ)在服務(wù)器的專(zhuān)有名詞為“SQLLite”(我終于知道他是干什么的了)
使用SQLLite數(shù)據(jù)庫(kù),需要兩個(gè)必要步驟:
創(chuàng)建數(shù)據(jù)庫(kù)訪問(wèn)對(duì)象
使用事務(wù)處理</span></p>
<div class="cnblogs_code">
<pre><span style="COLOR: #000000">創(chuàng)建對(duì)象:
openDatabase(dbName, version, dbDesc, size)</span></pre>
<pre><span style="COLOR: #000000">實(shí)際訪問(wèn):
db.transaction(function () {
tx.excuteSql('create table ......');
});</span></pre>
<pre><span style="COLOR: #000000">數(shù)據(jù)查詢(xún):
excuteSql(sql, [], dataHandler, errorHandler)//后面兩個(gè)為回調(diào)函數(shù);[]估計(jì)是做sql注入處理
光說(shuō)不練假把式,我們來(lái)實(shí)際操作一番,使用數(shù)據(jù)庫(kù)實(shí)現(xiàn)web通訊錄(左思右想還是用上了jQuery):
做的時(shí)候居然發(fā)現(xiàn)我的FF不支持本地?cái)?shù)據(jù)庫(kù)!??!以下是用chrome完成的簡(jiǎn)單的通訊錄:
通訊錄
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
span{ cursor: pointer;}
</style>
<script src="../jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var search = $('#search');
var btSearch = $('#btSearch');
var phoneBook = $('#phoneBook');
var name = $('#name');
var phone = $('#phone');
var add = $('#add');
//開(kāi)始程序
var db = openDatabase('phoneBook', '', 'my', 102400);
init();
add.click(function () {
save(name.val(), phone.val());
});
btSearch.click(function () {
init(search.val())
});
$('#phoneBook span').click(function () {
deleteByName($(this).attr('name'));
s = '';
});
//初始化界面
function init(name) {
db.transaction(function (tx) {
tx.executeSql('create table if not exists phoneBook(name text, phone text)', []);
var sql = 'select * from phoneBook where 1=1';
var param = [];
if (name) {
sql += ' and name=? ';
param.push(name);
}
tx.executeSql(sql, param, function (tx, rs) {
phoneBook.html('');
for (var i = 0, len = rs.rows.length; i < len; i++) {
var data = rs.rows.item(i);
showData(data);
}
});
});
}
function showData(data) {
var str = '<div>姓名:' + data.name + ';電話:' + data.phone + ' <span onclick="del(\'' + data.name + '')" >刪除</span></div>';
phoneBook.append($(str));
}
//刪除數(shù)據(jù)
function deleteByName(name) {
db.transaction(function (tx) {
tx.executeSql('delete from phoneBook where name=?', [name], function (tx, rs) {
init();
})
});
}
window.del = deleteByName;
//增加
function save(name, phone) {
db.transaction(function (tx) {
tx.executeSql('insert into phoneBook values(?, ?)', [name, phone], function (tx, rs) {
var d = {};
d.name = name;
d.phone = phone;
showData(d);
})
});
}
});
</script>
</head>
<body>
<h1>
本地?cái)?shù)據(jù)庫(kù)實(shí)現(xiàn)web通訊錄</h1>
<input type="text" id="search" placeholder="聯(lián)系人姓名" />
<button id="btSearch">
搜索</button>
<div id="phoneBook">
</div>
<hr />
姓名:<input type="text" id="name" />
手機(jī):<input type="text" id="phone" />
<button id="add">
添加到通訊錄</button>
</body>
</html>
![](/d/20211016/a5e865049b4a252627cd4a328b84f17a.gif)
結(jié)語(yǔ)
對(duì)于搞過(guò)后端的同學(xué),這章東西其實(shí)也是非常簡(jiǎn)單的,我再一次涌起了這種想法:
其實(shí)HTML5就是HTML4+api接口,目的就是讓我們可以用js做更多事情罷了。