HTML 5中的存储及离线应用(一)

本系列来源于Lynda.Com.HTML5.Local.Storage.And.Offline.Applications.In.Depth,我仅做了整理的工作。


先来点知识点讲解,HTML 5提供了以下几种存储方式:

  1. Local Storage;
  2. Session Storage;
  3. Web SQL Storage;
  4. Indexed database(IndexedDB);

前两种:

  1. 是web存储或者说DOM存储;
  2. 被设计用来替换之前的cookie存储方式;
  3. 其中Local Storage可持久化而Session Storage不可持久化;
  4. 这两种方式均使用Storage接口。
  5. IE 8、Firefox 3.6、Safari 4、Chrome 4。。。都支持;

Web SQL Storage:

  1. 使用SQLite 3引擎,这个好处多了;
  2. IE/Firefox暂无支持计划(杯具,为什么主流的都木有支持捏);

IndexedDB:

  1. Key-Value形式,非关系型数据;
  2. 在Firefox 4中已经支持,但其余浏览器支持还有段时间。。。;

OMG,是不是看到上面这么多感觉脑袋很乱。。。确实很无语啊,看样子标准统一还有待时日哦,而且看起来Chrome目前支持的最多耶。。。


好吧,前面的理论知识讲完了,下面我们开始来几个例子:


例子使用的js库文件:

/*
    bwH5LS.js by Bill Weinman 
    <http://bw.org/contact/>
    created 2011-04-16

    Copyright (c) 2011 The BearHeart Group, LLC
    This file may be used for personal educational purposes as needed. 
    Use for other purposes is granted provided that this notice is
    retained and any changes made are clearly indicated as such. 
*/

var _bwH5LS_version = "1.0.2";

// useful for finding elements
var element = function(id) { return document.getElementById(id); }
var errorMessage = undefined;

function getOpenDatabase() {
    try {
        if( !! window.openDatabase ) return window.openDatabase;
        else return undefined;
    } catch(e) {
        return undefined;
    }
}

function getLocalStorage() {
    try {
        if( !! window.localStorage ) return window.localStorage;
        else return undefined;
    } catch(e) {
        return undefined;
    }
}

function getSessionStorage() {
    try {
        if( !! window.sessionStorage ) return window.sessionStorage;
        else return undefined;
    } catch(e) {
        return undefined;
    }
}

function dispError( message ) {
    errorMessage = '<p class="error">' + message + '</p>';
    haveError = true;
}


function bwTable( wrap ) {
    this.wrap = ( wrap == undefined ) ? true : wrap;    // default to true
    this.rows = new Array();
    this.header = [];

    this.setHeader = function( row ) {
        this.header = row;
    }

    this.addRow = function( row ) {
        this.rows.push(row);
    }

    this.getRow = function ( index ) {
        return this.rows[index];
    }

    this.countRows = function () {
        return this.rows.length;
    }

    this.getTableHTML = function () {
        var a = '';
        if(this.wrap) a += '<table class="bwTable">\n';
        a += this.getHeaderHTML();
        for(var row in this.rows) {
            a += this.getRowHTML(this.rows[row]);
        }
        if(this.wrap) a += '</table>\n';
        return a;
    }

    this.getHeaderHTML = function () {
        if( this.header.length == 0 ) return '';
        var a = '<tr>';
        for( var cell in this.header ) {
            a += '<th>' + this.header[cell] + '</th>';
        }
        a += '</tr>\n';
        return a;
    }

    this.getRowHTML = function (row ) {
        var a = '<tr>';
        for( var cell in row ) {
            var v= row[cell];
            if(v == null) v = '<span class="red">NULL</span>';
            a += '<td>' + v + '</td>';
        }
        a += '</tr>\n';
        return a;
    }

    this.writeTable = function () {
        document.write(this.getTableHTML());
    }

}

例子使用的css文件:

/*
    main.css by Bill Weinman 
    <http://bw.org/contact/>
    created 2011-04-16

    Copyright (c) 2011 The BearHeart Group, LLC
    This file may be used for personal educational purposes as needed. 
    Use for other purposes is granted provided that this notice is
    retained and any changes made are clearly indicated as such. 

    v 1.0.1 - bw 2011-04-19
*/

/* -------- color guide (From Explore California) ----------
#3c6b92 : main blue
#6acce2 : light blue
#2c566a : teal accent
#193742 : dark blue
#e1d8b9 : sand accent
#cb7d20 : orange accent
#51341a : brown
#995522 : dark orange (used for links or high contrast accents)
#cb202a : red accent (this color does not encode well, use only for small accents)
#896287 : purple
*/

/* reasonable reset */
html, body, div, section, article, aside, header, hgroup, footer, nav, h1, h2, h3, h4, h5, h6, table, tr, td,
p, blockquote, address, time, span, em, strong, img, ol, ul, li, dl, dt, figure, canvas, video {
    margin: 0;
    padding: 0;
    border: 0;
}

body  {
    font-family: Georgia, serif;    /* default page font */
    background-color: #3c6b92;
}

.red {
    color: #cb202a;
}

p.message, p.error {
    font: normal 1em Helvetica, Arial, sans-serif;
    padding: 0 3px;
}

p.message {
    border: 1px solid #995522;
    background-color: #e1d8b9;
    color: black;
}

p.error {
    border: 1px solid #193742;
    background-color: #cb202a;
    color: white;
}

#content {
    width: 85%;
    margin: 20px auto;
    padding: 5px;
    background-color: white;
    min-height: 300px;
}

#content h1, #content h2 {
    font: normal 1.4em Helvetica, Arial, sans-serif;
    color: #3c6b92;
}

#content p, h1, h2, h3 {
    margin-bottom: .5em;
}

#content h1 {
    border-bottom: solid 2px #3c6b92;
}

#content h2.error {
    color: #cb7d20;
}

/* bwTable */

.bwTable {
    background: #c3cebc;
    margin-bottom: .5em;
    border: 1px solid #995522;
    border-collapse: collapse;
}

.bwTable tr, .bwTable td, .bwTable th {
    font: normal 1em Helvetica, Arial, sans-serif;
    text-align: left;
    border: solid 1px #995522;
    padding: 1px 3px;
}

.bwTable tr:nth-child(odd) {
    background: #e1d8b9;
}

.bwTable th {
    background: #193742;
    color: #c3cebc;
    border: solid 1px #51341a;
}

.bwTable td {
    min-width: 100px;
}

/* form */

#form {
    margin-bottom: 10px;
    border-bottom: 2px solid #3c6b92;
}

#form input[type=text] {
    width: 300px;
}

#form td.button, #form td.label {
    text-align: right;
}

#form td.label {
    padding-right: 3px;
}

第一个例子,使用Local Storage存储:

<?xml version="1.0" encoding="utf-8"?>
<!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">

<!-- 
    template.html by Bill Weinman 
    <http://bw.org/contact/>
    created 2011-04-16

    Copyright (c) 2011 The BearHeart Group, LLC
    This file may be used for personal educational purposes as needed. 
    Use for other purposes is granted provided that this notice is
    retained and any changes made are clearly indicated as such. 
-->

<head>
    <title>
        localStorage example
    </title>
    <link rel="stylesheet" type="text/css" href="../CSS/main.css">
    <script language="javascript" src="../Javascript/bwH5LS.js"></script>
    <script language="javascript">
        var t = new bwTable();
        var db = getLocalStorage() || dispError('Local Storage not supported.');
		// 得到存储对象
        function getLocalStorage() {
            try {
                if( !! window.localStorage ) return window.localStorage;
            } catch(e) {
				// 浏览器不支持的话返回未定义对象
                return undefined;
            }
        }
        
        function dispResults() {
            if(errorMessage) {
                element('results').innerHTML = errorMessage;
                return;
            }
            
			// 增加记录
            db.setItem('traveler', 'Bill');
            db.setItem('destination', 'Ventura');
            db.setItem('transportation', 'Airplane');
			// 删除记录
			//db.removeItem('traveler');
			// 清除所有记录
			//db.clear();

            var t = new bwTable();
			// 获取数据并显示在表格中
            t.addRow( ['traveler', db.getItem('traveler')] );
            t.addRow( ['destination', db.getItem('destination')] );
            t.addRow( ['transportation', db.getItem('transportation')] );
			// 表格嵌入HTML文档
            element('results').innerHTML = t.getTableHTML();
        }

        function dbGo() {
            if(errorMessage) return;
            dispResults();
        }

        function initDisp() {
            dispResults();
        }

        window.onload = function() {
            initDisp();
        }
    </script>
</head>

<body>

<div id="content">

    <h1> 
        localStorage example
    </h1>
    
    <div id="form">
        <form id="travelForm">
            <table class="form">
                <tr><td class="label"> Traveler </td><td> <input type="text" name="traveler" /> </td></tr>
                <tr><td class="label"> Destination </td><td> <input type="text" name="destination" /> </td></tr>
                <tr><td class="label"> Transportation </td><td> <input type="text" name="transportation" /> </td></tr>
                <tr><td colspan="2" class="button"> <input id="formSubmit" type="button" value="Go" onClick="javascript:dbGo()" /> </td></tr>
            </table>
        <input id="inputAction" type="hidden" name="action" value="add" />
        <input id="inputKey" type="hidden" name="key" value="0" />
        </form>
    </div>
    
    <div id="results">
    <!-- results show here -->
    </div>
    
</div>
</body>
</html>

第二个例子,在第一个例子的基础上将内容通过表格内控件值获取:

<?xml version="1.0" encoding="utf-8"?>
<!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">

<!-- 
    template.html by Bill Weinman 
    <http://bw.org/contact/>
    created 2011-04-16

    Copyright (c) 2011 The BearHeart Group, LLC
    This file may be used for personal educational purposes as needed. 
    Use for other purposes is granted provided that this notice is
    retained and any changes made are clearly indicated as such. 
-->

<head>
    <title>
        localStorage example
    </title>
    <link rel="stylesheet" type="text/css" href="../CSS/main.css">
    <script language="javascript" src="../Javascript/bwH5LS.js"></script>
    <script language="javascript">
        var t = new bwTable();
        var db = getLocalStorage() || dispError('Local Storage not supported.');

        function getLocalStorage() {
            try {
                if( !! window.localStorage ) return window.localStorage;
            } catch(e) {
                return undefined;
            }
        }
        
        function dispResults() {
            if(errorMessage) {
                element('results').innerHTML = errorMessage;
                return;
            }
            
            var t = new bwTable();
            t.addRow( ['traveler', db.getItem('traveler')] );
            t.addRow( ['destination', db.getItem('destination')] );
            t.addRow( ['transportation', db.getItem('transportation')] );
            element('results').innerHTML = t.getTableHTML();
        }

        function dbGo() {
            if(errorMessage) return;
            var f = element('travelForm');
            db.setItem('traveler', f.elements['traveler'].value);
            db.setItem('destination', f.elements['destination'].value);
            db.setItem('transportation', f.elements['transportation'].value);
            dispResults();
        }

        function dbClear() {
            if(errorMessage) return;
            db.clear();
            dispResults();
        }
        
        function initDisp() {
            dispResults();
        }

        window.onload = function() {
            initDisp();
        }
    </script>
</head>

<body>

<div id="content">

    <h1> 
        localStorage example
    </h1>
    
    <div id="form">
        <form id="travelForm">
            <table class="form">
                <tr><td class="label"> Traveler </td><td> <input type="text" name="traveler" /> </td></tr>
                <tr><td class="label"> Destination </td><td> <input type="text" name="destination" /> </td></tr>
                <tr><td class="label"> Transportation </td><td> <input type="text" name="transportation" /> </td></tr>
                <tr><td colspan="2" class="button">
                    <input id="formSubmit" type="button" value="Clear" onClick="javascript:dbClear()" />
                    <input id="formSubmit" type="button" value="Go" onClick="javascript:dbGo()" />
                </td></tr>
            </table>
        <input id="inputAction" type="hidden" name="action" value="add" />
        <input id="inputKey" type="hidden" name="key" value="0" />
        </form>
    </div>
    
    <div id="results">
    <!-- results show here -->
    </div>
    
</div>
</body>
</html>

注意上面这个例子中,并未初始化三个表格中的值,但浏览器关闭后重新打开仍然可以显示关闭之前保存的值。而且可以测试不同的浏览器保存的值是不一样滴。。。



下面这个例子我们将原来使用的Local Storage换成Session Storage:

<?xml version="1.0" encoding="utf-8"?>
<!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">

<!-- 
    template.html by Bill Weinman 
    <http://bw.org/contact/>
    created 2011-04-16

    Copyright (c) 2011 The BearHeart Group, LLC
    This file may be used for personal educational purposes as needed. 
    Use for other purposes is granted provided that this notice is
    retained and any changes made are clearly indicated as such. 
-->

<head>
    <title>
        sessionStorage example
    </title>
    <link rel="stylesheet" type="text/css" href="../CSS/main.css">
    <script language="javascript" src="../Javascript/bwH5LS.js"></script>
    <script language="javascript">
        var t = new bwTable();
        var db = getSessionStorage() || dispError('Session Storage not supported.');

        function getSessionStorage() {
            try {
				// 这里换成sessionStorage
                if( !! window.sessionStorage ) return window.sessionStorage;
            } catch(e) {
                return undefined;
            }
        }
        
        function dispResults() {
            if(errorMessage) {
                element('results').innerHTML = errorMessage;
                return;
            }
            
            var t = new bwTable();
            t.addRow( ['traveler', db.getItem('traveler')] );
            t.addRow( ['destination', db.getItem('destination')] );
            t.addRow( ['transportation', db.getItem('transportation')] );
            element('results').innerHTML = t.getTableHTML();
        }

        function dbGo() {
            if(errorMessage) return;
            var f = element('travelForm');
            db.setItem('traveler', f.elements['traveler'].value);
            db.setItem('destination', f.elements['destination'].value);
            db.setItem('transportation', f.elements['transportation'].value);
            dispResults();
        }

        function dbClear() {
            if(errorMessage) return;
            db.clear();
            dispResults();
        }
        
        function initDisp() {
            dispResults();
        }

        window.onload = function() {
            initDisp();
        }
    </script>
</head>

<body>

<div id="content">

    <h1> 
        sessionStorage example
    </h1>
    
    <div id="form">
        <form id="travelForm">
            <table class="form">
                <tr><td class="label"> Traveler </td><td> <input type="text" name="traveler" /> </td></tr>
                <tr><td class="label"> Destination </td><td> <input type="text" name="destination" /> </td></tr>
                <tr><td class="label"> Transportation </td><td> <input type="text" name="transportation" /> </td></tr>
                <tr><td colspan="2" class="button">
                    <input id="formSubmit" type="button" value="Clear" onClick="javascript:dbClear()" />
                    <input id="formSubmit" type="button" value="Go" onClick="javascript:dbGo()" />
                </td></tr>
            </table>
        <input id="inputAction" type="hidden" name="action" value="add" />
        <input id="inputKey" type="hidden" name="key" value="0" />
        </form>
    </div>
    
    <div id="results">
    <!-- results show here -->
    </div>
    
</div>
</body>
</html>


结果我们发现只要浏览器的标签页关闭,数据都不在了,这样大家能够清楚了解Local Storage和Session Storage的差别了吧。。。

ok,今天就到这里,后面接着讲SQL Storage和IndexedDB。

你可能感兴趣的:(JavaScript,html,function,存储,Class,input)