基於 HTML5 的資料存放區

來源:互聯網
上載者:User

標籤:

以前想做個靜態網頁APP。最初的思路是用本地檔案儲存體資料,後來發現在手機上運行時,檔案無法找到。

經過了長達幾個月的搜尋(實際也就幾天),沒有找到合適的方法。

就在絕望的時候,無意間搜到基於HTML5的各種儲存資料的方法。在此簡單與大家分享一下。

前四種是從http://www.hightopo.com/blog/344.html截取。

Cookie

最古老的儲存方式為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";      }}

 

LocalStorage

最簡單的儲存方式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‘];            }  }
Indexed Database 

Indexed Database,也可簡稱為 IndexedDB(以前被稱作 WebSimpleDB),同樣是一個 網頁用戶端儲存結構化資料的規範,在 2009 年由 Oracle 提出。

如果說 Web SQL Databae 在用戶端實現了 傳統的 SQL 資料庫操作,那麼 Indexed Database 更類似於 NoSQL 的形式來操作資料庫 , 其中最重要的是 Indexed Database 不使用 SQL 作為查詢語言。

其資料存放區可以不需要固定的表格模式,也經常會避免使用 SQL 的 JOIN 操作,並且一般具有水平可擴充性。

目前 W3C 官方也把焦點 投到對 Indexed Database 規範的制定當中來,而 Microsoft 和 Mozilla 是對這個規範重要的兩個推動者,Firefox 4 以上已經部分實現了 Indexed DB API,並且 IE 10 中也將實現 Indexed DB API。由於在手機等行動裝置的瀏覽器中都沒有實現 Indexed DB API,所以其還有一定的局限性,但這並不妨礙它作為未來的 HTML5 的焦點而存在。

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‘);        }            };}

 

瀏覽器支援

支援:IE(10.0)FireFox(4.0~12.0)Chrome(10.0~18.0)

不支援:IE(6.0~9.0)Safari(3.1~6.0)Opera(10.5~12.0)iOS Safari(3.2~5.0)Android Browser(2.1~4.0)

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‘);         });     });   }
 Web SQL Database

HTML5 的 Web SQL Database 用本地和會話儲存實現簡單的對象持久化。

對於 HTML5,也許最有用的就是它新推出的“Web Storage” API。對於簡單的索引值對(比如應用程式設定)或簡單對象(如應用程式狀態)進行儲存,使用本地和會話儲存能夠很好地完成,但是對繁瑣的關係資料進行處理的時候,它就力所不及了,而這正是 HTML5 的“Web SQL Database” API 借口的應用所在。

但W3C 官方在 2011 年 11 月聲明已經不再維護 Web SQL Database 規範。

如果說 Web SQL Databae 在用戶端實現了 傳統的 SQL 資料庫操作,那麼 Indexed Database 更類似於 NoSQL 的形式來操作資料庫 , 其中最重要的是 Indexed Database 不使用 SQL 作為查詢語言。

目前 W3C 官方也把焦點 投到對 Indexed Database 規範的制定當中來,而 Microsoft 和 Mozilla 是對這個規範重要的兩個推動者,Firefox 4 以上已經部分實現了 Indexed DB API,並且 IE 10 中也將實現 Indexed DB API。由於在手機等行動裝置的瀏覽器中都沒有實現 Indexed DB API,所以其還有一定的局限性,但這並 不妨礙它作為未來的 HTML5 的焦點而存在。

詳細資料在其它文中說明。

  

瀏覽器支援

支援:FireFox(4.0~12.0)Chrome(10.0~18.0)Safari(3.1~6.0)Opera(10.5~12.0)iOS Safari(3.2~5.0)Android Browser(2.1~4.0)

不支援:IE(6.0~10.0)

 

基於 HTML5 的資料存放區

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.