DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> HTML基礎知識 >> HTML5詳解 >> HTML5 Web 客戶端五種離線存儲方式匯總
HTML5 Web 客戶端五種離線存儲方式匯總
編輯:HTML5詳解     

最近折騰Html5游戲需要離線存儲功能,便把目前可用的幾種Html5存儲方式研究了下,基於HT for Web寫了個綜合的實例,分別利用了CookIE、WebStorage、IndexedDB以及FileSystem四種本地離線存儲方式,對燃氣監控系統的表計位置、朝向、開關以及表值等信息做了CURD的存取操作。

Html5的存儲還有一種Web SQL Database方式,雖然還有浏覽器支持,是唯一的關系數據庫結構的存儲,但W3C以及停止對其的維護和發展,所以這裡我們也不再對其進行介紹:Beware. This specification is no longer in active maintenance and the Web Applications Working Group does not intend to maintain it further.

Screen Shot 2014-12-22 at 1.39.12 AM

整個示例主要就是將HT for Web的DataModel數 據模型信息進行序列化和反序列化,這個過程很簡單通過dataModel.serialize()將模型序列化成JSON字符串,通過 dataModel.deserialize(jsonString)將JSON字符串內存反序列化出模型信息,而存儲主要就是主要就是針對JSON字符 串進行操作。

先介紹最簡單的存儲方式LocalStorage,代碼如下,幾乎不用介紹就是Key-Value的簡單鍵值對存儲結構,Web Storage除了localStorage的持久性存儲外,還有針對本次回話的sessionStorage方式,一般情況下localStorage較為常用,更多可參考 http://www.w3.org/TR/webstorage/

function save(dataModel){
    var value = dataModel.serialize();
    window.localStorage["DataModel"] = value;
    window.localStorage["DataCount"] = dataModel.size();
    console.log(dataModel.size() + " datas are saved");
    return value;
}
function restore(dataModel){  
    var value = window.localStorage["DataModel"];
    if(value){
        dataModel.deserialize(value);
        console.log(window.localStorage["DataCount"] + " datas are restored");
        return value;
    }    
    return "";
}
function clear(){
    if(window.localStorage["DataModel"]){
        console.log(window.localStorage["DataCount"] + " datas are cleared");
        delete window.localStorage["DataModel"];
        delete window.localStorage["DataCount"];         
    }   
}

最古老的存儲方式為CookIE,本例中我只能保存一個圖元的信息,這種存儲方式存儲內容很有限,只適合做簡單信息存儲,存取接口設計得極其反人類,為了介紹Html5存儲方案的完整性我順便把他給列上:

function getCookIEValue(name) {
    if (document.cookIE.length > 0) {
        var start = document.cookIE.indexOf(name + "=");
        if (start !== -1) {
            start = start + name.length + 1;
            var end = document.cookIE.indexOf(";", start);
            if (end === -1){
                end = document.cookIE.length;
            }
            return unescape(document.cookIE.substring(start, end));
        }
    }
    return "";
}
function save(dataModel) {
    var value = dataModel.serialize();
    document.cookIE = "DataModel=" + escape(value);
    document.cookIE = "DataCount=" + dataModel.size();    
    console.log(dataModel.size() + " datas are saved");
    return value;
}
function restore(dataModel){  
    var value = getCookIEValue("DataModel");
    if(value){
        dataModel.deserialize(value);
        console.log(getCookIEValue("DataCount") + " datas are restored");
        return value;
    }    
    return "";
}
function clear() {
    if(getCookIEValue("DataModel")){
        console.log(getCookIEValue("DataCount") + " datas are cleared");
        document.cookIE = "DataModel=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
        document.cookIE = "DataCount=; expires=Thu, 01 Jan 1970 00:00:00 UTC";   
    }
}

如今比較實用強大的存儲方式為Indexed Database API,IndexedDB 可以存儲結構對象,可構建key和index的索引方式查找,目前各浏覽器的已經逐漸支持IndexedDB的存儲方式,其使用代碼如下,需注意 IndexedDB的很多操作接口類似NodeJS的異步回調方式,特別是查詢時連cursor的continue都是異步再次回調onsuccess函 數的操作方式,因此和NodeJS一樣使用上不如同步的代碼容易。

request = indexedDB.open("DataModel");
request.onupgradeneeded = function() {  
    db = request.result;
    var store = db.createObjectStore("meters", {keyPath: "id"});
    store.createIndex("by_tag", "tag", {unique: true});
    store.createIndex("by_name", "name");  
};
request.onsuccess = function() {
    db = request.result;
};

function save(dataModel){
    var tx = db.transaction("meters", "readwrite");
    var store = tx.objectStore("meters");
    dataModel.each(function(data){
        store.put({
            id: data.getId(),
            tag: data.getTag(),
            name: data.getName(),
            meterValue: data.a("meter.value"),
            meterAngle: data.a("meter.angle"),
            p3: data.p3(),
            r3: data.r3(),
            s3: data.s3()
        });    
    });   
    tx.oncomplete = function() {
        console.log(dataModel.size() + " datas are saved");
    };    
    return dataModel.serialize();
}
function restore(dataModel){     
    var tx = db.transaction("meters", "readonly");
    var store = tx.objectStore("meters");
    var req = store.openCursor();  
    var nodes = [];
    req.onsuccess = function() {        
        var res = req.result;
        if(res){
            var value = res.value;
            var node = createNode();
            node.setId(value.id);
            node.setTag(value.tag);
            node.setName(value.name);                        
            node.a({
                "meter.value": value.meterValue,
                "meter.angle": value.meterAngle
            });
            node.p3(value.p3);                    
            node.r3(value.r3);
            node.s3(value.s3);
            nodes.push(node);             
            res.continue();
        }else{
            if(nodes.length){
                dataModel.clear();
                nodes.forEach(function(node){
                    dataModel.add(node);                         
                });
                console.log(dataModel.size() + " datas are restored");
            }             
        }       
    };    
    return "";
}
function clear(){
    var tx = db.transaction("meters", "readwrite");
    var store = tx.objectStore("meters");
    var req = store.openCursor();
    var count = 0;
    req.onsuccess = function(event) {        
        var res = event.target.result;
        if(res){
            store.delete(res.value.id);
            res.continue();
            count++;
        }else{
            console.log(count + " datas are cleared");
        }         
    };

}

最後是FileSystem API相當於操作本地文件的存 儲方式,目前支持浏覽器不多,其接口標准也在發展制定變化中,例如在我寫這個代碼時大部分文獻使用的webkitStorageInfo已被 navigator.webkitPersistentStorage和navigator.webkitTemporaryStorage替代,存儲的 文件可通過filesystem:http://www.hightopo.com/persistent/meters.txt’的URL方式在 Chrome浏覽器中查找到,甚至可通過filesystem:http://www.hightopo.com/persistent/類似目錄的訪 問,因此也可以動態生成圖片到本地文件,然後通過filesystem:http:***的URL方式直接賦值給img的Html元素的src訪問,因此 本地存儲打開了一扇新的門,相信以後會冒出更多稀奇古怪的奇葩應用。

navigator.webkitPersistentStorage.queryUsageAndQuota(function (usage, quota) {
        console.log("PERSISTENT: " + usage + "/" + quota + " - " + usage / quota + "%");
    }
);
navigator.webkitPersistentStorage.requestQuota(2 * 1024 * 1024,
    function (grantedBytes) {
        window.webkitRequestFileSystem(window.PERSISTENT, grantedBytes,
            function (fs) {
                window.fs = fs;
            });
    }
);
function save(dataModel) {
    var value = dataModel.serialize();
    fs.root.getFile("meters.txt", {create: true}, function (fileEntry) {
        console.log(fileEntry.toURL());
        fileEntry.createWriter(function (fileWriter) {
            fileWriter.onwriteend = function () {
                console.log(dataModel.size() + " datas are saved");
            };
            var blob = new Blob([value], {type: "text/plain"});
            fileWriter.write(blob);
        });
    });
    return value;
}
function restore(dataModel) {
    fs.root.getFile("meters.txt", {}, function (fileEntry) {
        fileEntry.file(function (file) {
            var reader = new FileReader();
            reader.onloadend = function (e) {
                dataModel.clear();
                dataModel.deserialize(reader.result);
                console.log(dataModel.size() + " datas are restored");
            };
            reader.readAsText(file);
        });
    });
    return "";
}
function clear() {
    fs.root.getFile("meters.txt", {create: false}, function(fileEntry) {
        fileEntry.remove(function() {
            console.log(fileEntry.toURL() + " is removed");
        });
    });    
}

Screen Shot 2014-12-22 at 12.53.48 AM

Browser-Side的存儲方式還在快速的發展中,其實除了以上幾種外還有Application Cache,相信將來還會有新秀出現,雖然“雲”是大趨勢,但客戶端並非要走極端的“瘦”方案,這麼多年冒出了這麼多客戶端存儲方式,說明讓客戶端更強大 的市場需求是強烈的,當然目前動蕩階段苦逼的是客戶端程序員,除了要適配Mouse和Touch,還要適配各種屏,如今還得考慮適配各種存儲,希望本文能 在大家選型客戶端存儲方案時有點幫助,最後上段基於HT for Web操作Html5存儲示例的視頻效果:http://v.youku.com/v_show/id_XODUzODU2MTY0.Html

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved