Client storage is primarily handy for offline use by some apps. What is the method for client storage today?
Say in the first sentence: All client-side storage has a principle: read and write data must be in the same domain
1 cookies
Cookie is a very old technology, because it is old, so compatibility is good. The code for the common JS operation cookie is as follows:
function Setcookie (c_name,value,expiredays) {var exdate=new Date () exdate.setdate (Exdate.getdate () +expiredays) document.cookie=c_name+ "=" +escape (value) + ((expiredays==null)? "": "; expires=" +exdate.togmtstring ())}function GetCookie (c_name) {if (document.cookie.length>0) { c_ Start=document.cookie.indexof (c_name + "=") if (c_start!=-1) { C_start=c_start + c_name.length+1 c_ End=document.cookie.indexof (";", C_start) if (c_end==-1) c_end=document.cookie.length return unescape ( Document.cookie.substring (c_start,c_end) } }return ""}
Code is from the W3school there, the big night I also do not know to write, please forgive me.
Use cookies as a local storage advantage: good compatibility , shortcomings: cumbersome operation, can only save simple data, will expire, site Settings httponly, JS will not be able to operate cookies .
2 Web Storage
WebStorage is a HTML5 in the WebApplication to provide a storage API, the current mainstream of the new version of the browser support, of course IE789 you have no way. WebStorage is mainly divided into localstorage and sessionstorage two species.
Sessionstorage is a global object that maintains the storage space that is valid during a page session. The page session cycle lasts as long as the browser is open. Page sessions also persist when the page is re-loaded (reload) or restored (restores). A new session is initialized for each new page opened in a new tab or in a new window.
Localstorage is also a global variable whose life cycle is longer than sessionstorage. Both Localstorage and sessionstorage inherit from storage so they use the same.
Interface Storage { readonly attribute unsigned long length; [Indexgetter] Domstring key (in unsigned long index); [Namegetter] Domstring GetItem (in Domstring key); [Namesetter] void SetItem (in Domstring key, in domstring data); [Namedeleter] void RemoveItem (in domstring key); void clear ();};
Save the data to the current session's storage space Sessionstorage.setitem ("username", "John");//Access Data alert ("username =" + Sessionstorage.getitem (" Username "));
WebStorage Advantages: The use of simple and convenient , disadvantage:some version of IE does not support, can not save complex objects, must first be converted to JSON string, no index search efficiency is not high, only synchronous read and write operations, when the data is written relatively large can cause JS engine jam.
3 IndexedDB
Indexeddb is a database based on JavaScript object inheritance that supports transactions while supporting both asynchronous and synchronous read and write. INDEXEDDB can be stored in objects, of course, the object to be able to structure cloning (structured clone), while it also provides indexing function, greatly improve the efficiency of the search. Generally speaking, the size of the INDEXEDDB is not limited, when the size of more than 50MB, the browser will pop up a dialog to ask the user whether to increase the size of the data.
var request = Window.indexedDB.open ("Candydb", "My Candy Store Database"); request.onsuc Cess = function (event) {var db = Event.result; if (db.version! = "1") {//User ' s first visit, initialize database. var createdobjectstorecount = 0; var objectstores = [{name: "Kids", KeyPath: "id", autoincrement:true}, {name: "Candy", KeyPath: "id", Autoi Ncrement:true}, {name: "Candysales", KeyPath: "", autoincrement:true}]; function Objectstorecreated (event) {if (++createdobjectstorecount = = objectstores.length) {db.setversion ("1" ). onsuccess = function (event) {loaddata (db); }; }} for (var index = 0; index < objectstores.length; index++) {var params = Objectstores[index]; Request = Db.createobjectstore (Params.name, Params.keypath, params.autoincrement); request.onsuccess = objectstorecreated; }} else {//User hasBeen here before, no initialization required. LoadData (DB); }};var kids = [{name: "Anna"}, {name: "Betty"}, {name: "Christine"}]; var request = Window.indexedDB.open ("Candydb", "My Candy Store Database"); request.onsuc Cess = function (event) {var objectstore = Event.result.objectStore ("Kids"); for (var index = 0; index < kids.length; index++) {var kid = Kids[index]; Objectstore.add (kid). onsuccess = function (event) {document.getElementById ("display"). Textcontent = "Saved rec Ord for "+ Kid.name +" with id "+ Event.result; }; }};
Pros: support the transaction, support the index, can be deposited objects, the efficiency is good . Cons: using some trouble, it takes a while to get started .
4 Fileapi
In the latest version of MDN and the FILEAPI related documents only see FileReader related, this API can be combined with file forms and formdata to implement asynchronous upload files. Since there is no filewriter related documentation, we think for the time being that FILEAPI cannot implement this requirement for client storage .
function Startread () {//obtain INPUT element through DOM var file = document.getElementById (' file '). Files[0]; if (file) {getastext (file); }}function Getastext (readFile) {var reader = new FileReader (); Read file into memory as UTF-16 Reader.readastext (ReadFile, "UTF-16"); Handle progress, success, and errors reader.onprogress = UpdateProgress; Reader.onload = loaded; Reader.onerror = ErrorHandler;} function UpdateProgress (evt) {if (evt.lengthcomputable) {//evt.loaded and Evt.total are progressevent properties var loaded = (evt.loaded/evt.total); if (loaded < 1) {//increase the Prog bar length//style.width = (loaded * +) + "px"; }}}function Loaded (EVT) {///Obtain the Read file data var filestring = Evt.target.result; Handle UTF-16 file Dump if (Utils.regexp.isChinese (filestring)) {//chinese characters + Name validation} else { Run other CharSet test}//Xhr.send (filestring) }function ErrorHandler (evt) {if (Evt.target.error.name = = "Notreadableerror") {//The file could not being read}} 5 References
- Https://developer.mozilla.org/zh-CN/docs/Web/Guide/API/DOM/Storage/Storage
- Https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
- Https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/The_structured_clone_algorithm
- Https://developer.mozilla.org/en-US/docs/Web/API/FileReader
- http://www.w3.org/TR/FileAPI/
- http://www.w3.org/TR/file-writer-api/
WEB-Client storage in several ways