Table of Contents
HTML5的五种客户端离线存储方案
Home Backend Development PHP Tutorial HTML5的五种客户端离线存储方案_PHP教程

HTML5的五种客户端离线存储方案_PHP教程

Jul 12, 2016 am 09:05 AM
android

HTML5的五种客户端离线存储方案

最近折腾HTML5游戏需要离线存储功能,便把目前可用的几种HTML5存储方式研究了下,基于HT for Web写了个综合的实例,分别利用了Cookie、WebStorage、IndexedDB以及FileSystem四种本地离线存储方式,对燃气监控系统的表计位置、朝向、开关以及表值等信息做了CURD的存取操作。

http://www.hightopo.com/guide/guide/core/serialization/examples/example_exportimport.html

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/

functionsave(dataModel){varvalue=dataModel.serialize();window.localStorage['DataModel']=value;window.localStorage['DataCount']=dataModel.size();console.log(dataModel.size()+'datasaresaved');returnvalue;}functionrestore(dataModel){varvalue=window.localStorage['DataModel'];if(value){dataModel.deserialize(value);console.log(window.localStorage['DataCount']+'datasarerestored');returnvalue;}return'';}functionclear(){if(window.localStorage['DataModel']){console.log(window.localStorage['DataCount']+'datasarecleared');deletewindow.localStorage['DataModel'];deletewindow.localStorage['DataCount'];}}
Copy after login


最古老的存储方式为Cookie,本例中我只能保存一个图元的信息,这种存储方式存储内容很有限,只适合做简单信息存储,存取接口设计得极其反人类,为了介绍HTML5存储方案的完整性我顺便把他给列上:

functiongetCookieValue(name){if(document.cookie.length>0){varstart=document.cookie.indexOf(name+"=");if(start!==-1){start=start+name.length+1;varend=document.cookie.indexOf(";",start);if(end===-1){end=document.cookie.length;}returnunescape(document.cookie.substring(start,end));}}return'';}functionsave(dataModel){varvalue=dataModel.serialize();document.cookie='DataModel='+escape(value);document.cookie='DataCount='+dataModel.size();console.log(dataModel.size()+'datasaresaved');returnvalue;}functionrestore(dataModel){varvalue=getCookieValue('DataModel');if(value){dataModel.deserialize(value);console.log(getCookieValue('DataCount')+'datasarerestored');returnvalue;}return'';}functionclear(){if(getCookieValue('DataModel')){console.log(getCookieValue('DataCount')+'datasarecleared');document.cookie="DataModel=;expires=Thu,01Jan197000:00:00UTC";document.cookie="DataCount=;expires=Thu,01Jan197000:00:00UTC";}}
Copy after login


如今比较实用强大的存储方式为Indexed Database API,IndexedDB可以存储结构对象,可构建key和index的索引方式查找,目前各浏览器的已经逐渐支持IndexedDB的存储方式,其使用代码如下,需注意IndexedDB的很多操作接口类似NodeJS的异步回调方式,特别是查询时连cursor的continue都是异步再次回调onsuccess函数的操作方式,因此和NodeJS一样使用上不如同步的代码容易。

request=indexedDB.open("DataModel");request.onupgradeneeded=function(){db=request.result;varstore=db.createObjectStore("meters",{keyPath:"id"});store.createIndex("by_tag","tag",{unique:true});store.createIndex("by_name","name");};request.onsuccess=function(){db=request.result;};functionsave(dataModel){vartx=db.transaction("meters","readwrite");varstore=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()+'datasaresaved');};returndataModel.serialize();}functionrestore(dataModel){vartx=db.transaction("meters","readonly");varstore=tx.objectStore("meters");varreq=store.openCursor();varnodes=[];req.onsuccess=function(){varres=req.result;if(res){varvalue=res.value;varnode=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()+'datasarerestored');}}};return'';}functionclear(){vartx=db.transaction("meters","readwrite");varstore=tx.objectStore("meters");varreq=store.openCursor();varcount=0;req.onsuccess=function(event){varres=event.target.result;if(res){store.delete(res.value.id);res.continue();count++;}else{console.log(count+'datasarecleared');}};}
Copy after login


最后是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;});});functionsave(dataModel){varvalue=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()+'datasaresaved');};varblob=newBlob([value],{type:'text/plain'});fileWriter.write(blob);});});returnvalue;}functionrestore(dataModel){fs.root.getFile('meters.txt',{},function(fileEntry){fileEntry.file(function(file){varreader=newFileReader();reader.onloadend=function(e){dataModel.clear();dataModel.deserialize(reader.result);console.log(dataModel.size()+'datasarerestored');};reader.readAsText(file);});});return'';}functionclear(){fs.root.getFile('meters.txt',{create:false},function(fileEntry){fileEntry.remove(function(){console.log(fileEntry.toURL()+'isremoved');});});}
Copy after login


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

http://www.hightopo.com/guide/guide/core/serialization/examples/example_exportimport.html


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1068088.htmlTechArticleHTML5的五种客户端离线存储方案 最近折腾HTML5游戏需要离线存储功能,便把目前可用的几种HTML5存储方式研究了下,基于HT for Web写了个综合...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

Motorola Razr 50s shows itself as possible new budget foldable in early leak Motorola Razr 50s shows itself as possible new budget foldable in early leak Sep 07, 2024 am 09:35 AM

Motorola has released countless devices this year, although only two of them are foldables. For context, while most of the world has received the pair as the Razr 50 and Razr 50 Ultra, Motorola offers them in North America as the Razr 2024 and Razr 2

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

See all articles