HTML5-based data storage

Source: Internet
Author: User
Tags createindex

Used to be a static web App. The original idea was to store the data in a local file and later found that the file could not be found when it was running on the phone.

After months of searching (actually for a few days), no suitable method was found.

In desperation, the HTML5-based approach to preserving data was inadvertently discovered. Here is a simple to share with you.

The first four species are intercepted from http://www.hightopo.com/blog/344.html.

Cookies

The oldest storage method is a cookie, which stores content is limited, only suitable for simple information storage, access interface design is extremely anti-human, in order to introduce the integrity of the HTML5 storage scheme I gave him the list by the way:

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 ()+ ' datas is saved '); returnvalue;}functionRestore (datamodel) {varValue = Getcookievalue (' Datamodel '); if(value) {datamodel.deserialize (value); Console.log (Getcookievalue (' Datacount ') + ' datas is restored '); returnvalue; }       return‘‘;}functionClear () {if(Getcookievalue (' Datamodel ') {console.log (Getcookievalue (' Datacount ') + ' datas is cleared '); Document.cookie= "datamodel=; Expires=thu, Jan 1970 00:00:00 UTC "; Document.cookie= "datacount=; Expires=thu, Jan 1970 00:00:00 UTC "; }}

Localstorage

The simplest storage method Localstorage, Li Yong key-value simple key value to the storage structure, the WEB storage in addition to the Localstorage persistent storage, but also for this reply Sessionstorage way, Generally localstorage more commonly used, more can refer to http://www.w3.org/TR/webstorage/

functionSave (Datamodel) {varValue =datamodel.serialize (); window.localstorage[' Datamodel '] =value; window.localstorage[' Datacount '] =datamodel.size (); Console.log (Datamodel.size ()+ ' datas is saved '); returnvalue;}functionRestore (datamodel) {varValue = window.localstorage[' Datamodel ']; if(value) {datamodel.deserialize (value); Console.log (window.localstorage[' Datacount ' + ' datas is restored '); returnvalue; }       return‘‘;}functionClear () {if(window.localstorage[' Datamodel ']) {Console.log (window.localstorage[' Datacount ' + ' datas is cleared '); Deletewindow.localstorage[' Datamodel ']; Deletewindow.localstorage[' Datacount ']; }  }
Indexed Database

Indexed Database, also referred to as IndexedDB (formerly known as Websimpledb), is also a specification for WEB clients to store structured data, which was presented by Oracle in 2009.

If Web SQL Databae implements traditional SQL database operations on the client, then Indexed database is more like a NoSQL form of manipulating databases, the most important of which is Indexed database does not use SQL as a query Language.

Its data storage can not require a fixed tabular pattern, and often avoids the use of SQL JOIN operations, and generally has horizontal extensibility.

At present, the official also focus on the Indexed Database specification, while Microsoft and Mozilla are important to the specification of the two drivers, Firefox 4 has partially implemented the Indexed DB API, and IE The Indexed DB API will also be implemented in 10. Because Indexed DB API is not implemented in the browser of mobile devices such as mobile phones, there are some limitations, but this does not prevent it from being the focus of the future HTML5.

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.getNa Me (), 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 is saved ');        }; 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 ()+ ' datas is restored ');       }                    }          }; 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+ ' datas is cleared '); }            };}

Browser support

Support: IE (10.0) FireFox (4.0~12.0) Chrome (10.0~18.0)

Not supported: 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

Equivalent to the operation of local file storage, currently supports a few browsers, and its interface standards in the development of change, For example, in this code, most of the literature used by Webkitstorageinfo has been replaced by Navigator.webkitpersistentstorage and Navigator.webkittemporarystorage,

Stored files can be found in the Chrome browser via Filesystem:http://www.hightopo.com/persistent/meters.txt ' URL,

It can even be accessed by filesystem:http://www.hightopo.com/persistent/similar directories, so it is possible to dynamically generate images to local files,

The filesystem:http:*** URL is then assigned directly to the SRC access to the img HTML element, so the local store opens a new door, believing that more bizarre and exotic applications will emerge later.

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 ()+ ' datas is saved ');             }; 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 ()+ ' datas is restored ');             };         Reader.readastext (file);     });     }); return‘‘; } functionClear () {Fs.root.getFile (' Meters.txt ', {create:false},function(fileentry) {Fileentry.remove (function() {Console.log (Fileentry.tourl ()+ ' is removed ');     });   }); }
Web SQL Database

HTML5 's Web SQL Database implements Simple object persistence with local and session storage.

For HTML5, perhaps the most useful is its new "Web Storage" API. Storing simple key-value pairs (such as application settings) or simple objects (such as application state) can be done well with local and session storage, but when dealing with cumbersome relational data, it grasp, and this is HTML5 's "Web SQL Database" API The application of the pretext.

But the official statement in November 2011 declared that the Web SQL Database specification was no longer maintained.

If Web SQL Databae implements traditional SQL database operations on the client, then Indexed database is more like a NoSQL form of manipulating databases, the most important of which is Indexed database does not use SQL as a query Language.

At present, the official also focus on the Indexed Database specification, while Microsoft and Mozilla are important to the specification of the two drivers, Firefox 4 has partially implemented the Indexed DB API, and IE The Indexed DB API will also be implemented in 10. Because Indexed DB API is not implemented in the browser of mobile devices such as mobile phones, there are some limitations, but this does not prevent it from being the focus of the future HTML5.

Detailed information is described in the other article.

Browser support

Support: 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)

Not supported: IE (6.0~10.0)

HTML5-based data storage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.