HTML5 provides two new ways to store data on the client:
- Localstorage-Data storage with no time limit
- Sessionstorage-Data storage for a session
Cookie vs. WebStorage: The cookie flaw is very obvious
1. Data size: As a storage container, the size of the cookie is limited to around 4KB this is very pit daddy, especially for today's complex business logic requirements, 4KB capacity in addition to storing some configuration fields also simple single-value information, for most developers really do not know what to expect.
2. Security issue: Because the cookie in the HTTP request is passed in plaintext (https is not), the security issue is still very large.
3. Network Burden: We know that cookies are appended to each HTTP request and are to be transmitted in the header of HttpRequest and HttpResponse, so there is an implicit increase in unnecessary traffic loss.
Webstroage:
WebStorage provides two types of api:localstorage and sessionstorage, the difference between the two of the name has a general understanding, localstorage in the local persistent storage of data, unless explicitly deleted or emptied, The data stored by Sessionstorage is only valid during the session and is automatically deleted when the browser is closed. Two objects have a common API
- Length: Unique property, read-only, used to get the number of key-value pairs within the storage.
- Key: Gets the key name of the storage based on index
- GetItem: Gets the corresponding value within the storage based on key
- SetItem: Adding key-value pairs for storage
- RemoveItem: Delete key-value pairs based on key name
- Clear: Empty the storage object
Examples of use of webstroage:
varls=Localstorage; Console.log (ls.length);//0Ls.setitem (' name ', ' Byron '); Ls.setitem (' Age ', ' 24 '); Console.log (ls.length);//2 //Traverse Localstorage for(vari=0;i<ls.length;i++){ /*age:24 Name:byron*/ varkey=Ls.key (i); Console.log (Key+ ': ' +Ls.getitem (key)); } ls.removeitem (' Age '); for(vari=0;i<ls.length;i++){ /*Name:byron*/ varkey=Ls.key (i); Console.log (Key+ ': ' +Ls.getitem (key)); } ls.clear ();//0Console.log (ls.length);
Attention:
1. Because both Localstorage and Sessionstorage are objects, key-value pairs can also be obtained and modified through ". Key" or "[key]", but not recommended
Localstorage.username= ' Frank '; Console.log (localstorage[' userName ');
2. Although Localstorage is stored locally, different browser storage data is independent, so the localstorage stored on Chrome is not available on Firefox.
3. Localstorage and Sessionstorage can only store string types, and for complex objects can be handled using the stringify and parse of the JSON object provided by ECMAScript, and low version IE can be used json2.js