【讀書筆記】HTML5 Web存儲


PS:這里講web存儲,主要是在客戶端存儲的一些技術:cookie,localstorage,sessionstorage,WebSQL。  
 
Cookie
 
Cookie是HTML4中在客戶端存儲簡單用戶信息的一種方式,它的應用很多所以有必要回顧一下。它使用文本來存儲信息,當有應用程序使用cookie時,服務器端就會發送cookie到客戶端。客戶端瀏覽器將保存該信息。下一次頁面請求時,客戶端瀏覽器就會把cookie發送到服務器。 
 
優缺點:
1、簡答易用。
2、瀏覽器負責發送數據。
3、瀏覽器自動管理不同站點的cookie。
缺點:
1.使用簡單文本存儲數據,所以cookie的安全性很差。cookie保存在客戶端瀏覽器,很容易被客戶端盜取。
2.Cookie的存儲數據容量有限。上限為4kb。
3.cookie存儲的數量有限,多數瀏覽器上限為30或50個,ie6只支持每個域名存儲20個cookie。
4.如果瀏覽器的安全配置為最高,cookie將失效。
5.cookie不適合大量數據的存儲,因為cookie會由每個對服務器的請求來傳遞,從而造成cookie速度緩慢效率低下。
簡單的設置或獲取cookie
 function setCookie(name, value, expiredays) {
             var date = new Date();
             date.setDate(date.getDate() + expiredays);
             document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + date.toGMTString());
         }
         setCookie('username', 'Darren', 30);
         function getCookie(name) {
             if (document.cookie.length > 0) { 
                var start = document.cookie.indexOf(name + "=");  //通過String對象的indexOf()來檢查這個cookie是否存在,不存在就為 -1  
                 if (start != -1) {
                     start = start + name.length + 1; //最后這個+1其實就是表示"="號啦,這樣就獲取到了cookie值的開始位置
                  var end = document.cookie.indexOf(";", start);// indexOf()第二個參數表示指定的開始索引的位置 
                     if (end == -1) end = document.cookie.length;
                     return unescape(document.cookie.substring(start, end)); //通過substring()得到了值。想了解unescape()得先知道escape()是做什么的,都是很重要的基礎 
                 }
             }
             return "";
         }
View Code

也有Jquery.cookie.js可以用

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
View Code
 $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'cnblogs.com'});//設置
var cc = $.cookie('the_cookie');//獲取
  $.cookie('the_cookie', null);//刪除

Web Storage

HTML5 中的Web Storage提供了兩種在客戶端存儲數據的方法,即localStorage和sessionstorage。
localstorage是用於持久化的本地存儲,除非主動刪除數據,負責數據是永遠不會過期的。localstorage的機制和Cookie相似,都是key-value的形式存儲,對I/O進行操作;sessionstorage是將數據保存在session對象中,用戶關閉瀏覽器,數據就會刪除。不是一種持久化的本地存儲,僅僅是會話級別的存儲。
兩者實現的接口相同。
interface Storage{
 readonly attribute unsigned long length;
 getter DOMString key(in unsigned long index);
 getter any getItem(in DOMString key,in any data);
 deleter void removeItem(in DOMString key);
 void clear();
} 

優缺點

1、IE8下,每個獨立的存儲空間為10M,其他瀏覽器略有不同,但有比cookie要大很多。
2、內容不會發送到服務器。
3、更多豐富易用的接口,使得數據的操作更為簡便。
缺點:
1.瀏覽器會為每個域分配獨立的存儲空間。域A是無法訪問到域B的存儲空間。
2.本地數據未加密而且永遠不會過期,極易造成隱私泄露。
用法:
  window.sessionStorage.setItem('mykey', 'niqiu');
  window.sessionStorage.nikey = 'stone';
  alert(window.sessionStorage.getItem('mykey'));
  alert(window.sessionStorage.nikey);

 將一段Json存入localstorage:

var data = new Object();
        data.name = "stoneniqiu";
        data.age = "26";
        var str = JSON.stringify(data);
        localStorage.setItem(data.name, str);

        function getstone() {
            var raw = localStorage.getItem("stoneniqiu");
            var data = JSON.parse(raw);
            alert(data.name + data.age);
        }
        getstone();

用LS存儲用戶的操作記錄,個性化的代碼片段。對於性能和使用范圍可以看看這篇文章: 讓我們再談談瀏覽器資源加載優化

Web SQL

 Web SQL Database 允許應用通過一個異步JavaScript接口訪問SQLLite 數據庫,但IE,Firefox並沒有實現它,而且WHATWG也停止對Web Sql Database的開發。由於標准認定直接執行SQL語句不可取,Web Sql database 已經被索引數據庫(Indexed Database)所取代。

 

瀏覽器
說明
IE
不支持
FireFox
不支持
Opera
10.5及以上支持
Chrome
3.0及以上支持
Safari
3.2及以上支持。
HTML5 數據庫API主要包括3個核心方法
1.openDatabase:使用現有數據庫或創建新數據庫的方式創建數數據庫對象。
Database openDatabase(in DOMString name,in DOMString version,in DOMString displayName,in unsigned long estimatedSize,in optional DatabaseCallback creationCallback)

參數名稱不言而喻 腳本用法:

var db=openDatabase("myDb","0.1","A list of to do items",20000)

這樣就創建了一個數據庫。

2.transaction:允許用戶根據情況控制事務提交或回滾。完整定義:

transaction.executeSql(sqlquery,[],dataHandler,errorHandler):

sqlquery 為要執行的sql語句,[]這個數組表示sql語句中使用的參數數組。所有參數先用?號代替。然后依次將這些參數放在這個數組中。

腳本用法:

db.transaction(function(tx){})

實例:

transaction.executeSql("Update people set age-? where name=?;",[age,name]);
而第三個參數表示執行成功時調用的回調函數。
function dataHandler(transaction,errmsg){}
第四個參數是SQL執行出錯時的回調函數
function errorHandler(transaction,errmsg){}

3.executeSql:用於執行真實的SQL查詢。

實例:

 function initdb() {
            var name = ['C#', "C++", "C", "JavaScript", "Java", "PhP"];
            db.transaction(function(tx) {
                tx.executeSql('Create table if not exists mytable(id integer primary key autoincrement,name)');
                for (var i = 0; i < name.length; i++) {
                    tx.executeSql('insert into mytable(name) values(?)', [name[i]]);
                }
            });
        }

  initdb();

 一張表包含了用 "AUTOINCREMENT" 修飾的列時, sqlite 將自動創建表 "SQLITE_SEQUENCE"。如果想清空記錄,讓編號歸0,直接處理sqlite_sequence就可以了。

 db.transaction(function(tx) {
            tx.executeSql('create table if not exists t1(id unique,log)');
            tx.executeSql('insert into t1(id,log) values(1,"created a db")');
            tx.executeSql('insert into t1(id,log) values(1,"a good day")');
            tx.executeSql('insert into t1(id,log) values(1,"hello")');
        });

//讀取:
db.transaction(function(tx) {
            tx.executeSql('select * from t1', [], function(tx, results) {
                var len = results.rows.length, i;
                var msg = "<p>共有" + len + "條記錄</p>";
                document.getElementById("res").innerHTML = msg;
                for (i = 0; i < len; i++) {
                    msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
                    document.querySelector('#res').innerHTML += msg;
                }
            },null);
        });

 

IndexedDB

IndexedDB很像Nosql。能夠存儲可觀的結構化數據,一個單獨的數據庫項目的大小沒有限制。然而可能會限制每個 IndexedDB 數據庫的大小。這個限制(以及用戶界面對它進行斷言的方式)在各個瀏覽器上也可能有所不同。比如Firefox4中一個站點超過50M,Firefox會向用戶請求權限。在移動端是5M.

使用異步 API 方法調用完后會立即返回,而不會阻塞調用線程。

文檔中的示例:

 var request = indexedDB.open("library");
        request.onupgradeneeded = function () {
            // The database did not previously exist, so create object stores and indexes.
            var db = request.result;
            var store = db.createObjectStore("books", { keyPath: "isbn" });
            var titleIndex = store.createIndex("by_title", "title", { unique: true });
            var authorIndex = store.createIndex("by_author", "author");

            // Populate with initial data.
            store.put({ title: "Quarry Memories", author: "Fred", isbn: 123456 });
            store.put({ title: "Water Buffaloes", author: "Fred", isbn: 234567 });
            store.put({ title: "Bedrock Nights", author: "Barney", isbn: 345678 });
        };

        request.onsuccess = function () {
            db = request.result;
        };

 

更詳細的操作我這里也不贅述了,功能比較強大,支持group,filter等大家可以去看下面兩篇文章。

IndexedDatabase API  http://www.w3.org/TR/IndexedDB/

HTML5本地存儲:http://www.cnblogs.com/dolphinX/p/3415761.html

瀏覽器支持度:
 
 
小結:
本地存儲方式比較多,一般的需求還是做一些個性化的存儲。cookie和LS都是不錯的選擇,但是如果要支持離線,存儲的數據可能就需要用到IndexedDb這樣的存儲方式了。
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM