Webstorage [html5 local data processing], webstoragehtml5
1. What is webStorage?
WebStorage is a method used in html5 for local storage. In the past, we used cookies for storage;
2. What is the difference between them?
I. cookie problems:
I. A cookie needs to send a request to the server. The server returns a cookieId, which is stored in the browser cache and consumes a certain amount of bandwidth. [The cookie is sent along with the HTTP Request Header, which increases network traffic.]
II. The data capacity of cookie storage is limited. IE6 can only store 2 K of data, depending on the browser type;
Ii. While webstorage only needs to store data locally;
3. We can give a small example to illustrate
Eg: Enter the user name and password. When you click "1", save the data and click "2". The page can be refreshed;
Process:
I. Create an event
function MyClick1(){}
Ii. Obtain the user name of an id.
var username = $("#TxtUserName").val();
Iii. Obtain the password of an id.
var pwd = $("#TxtPwd").val();
Iv. How do we store data after the user name and password are obtained? There are two methods:
①. First: sessionStorege, used in Firefox2 + Firefox browser;
Life cycle: data stored in this way is only valid at the window level. Data stored locally can be obtained when the same window (or Tab) page is refreshed or redirected, when a new window or page is opened, the original data becomes invalid [only for the current page]
Disadvantage: IE does not support persistent data storage.
sessionStorage.setItem("k_username", username);
sessionStorage.setItem("k_pwd", pwd);
Note: sessionStorage. setItem is stored by key-value pairs;
②. Method 2: localStorage
LocalStorage is part of the Web Storage Internet Storage specification and is now supported in Firefox 3.5, Safari 4, and IE8.
Lifecycle: stored on the local drive C, closed by the browser;
Disadvantage: browsers of earlier versions are not supported.
localStorage.setItem("k_username", username); localStorage.setItem("k_pwd",pwd);
V. Print
Alert ("saved successfully! ");
Vi. Button 2 print all the above data
First print:
function MyClick2() { alert(sessionStorage.getItem("k_username")); alert(sessionStorage.getItem("k_pwd")); }
The second method is printing:
function MyClick2() { alert(localStorage.getItem("k_username")); alert(localStorage.getItem("k_pwd")) }
Result:
VII. Extension: removeItem method of localStorage
// What should I do if I want to delete the user name? Delete it by using its key, so that it is null when it is obtained // localStorage. removeItem ("k_username ");
Track local data:
Result:
VIII. clear method of localStorage
// If I want to clear all the data? LocalStorage has a method localStorage. clear ();
Result:
Code display:
1 <! DOCTYPE html> 2
4. Make a simple message board using webStorage [write JavaScript directly in html for the purpose of displaying the result]
1 <! DOCTYPE html> 2
Effect display: