In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Many novices are not very clear about the new experience of local storage in HTML5. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.
Why save data to the client?
Storing data on the client side can solve many problems and reduce unnecessary data transfer:
1. Can save the state of the program: the user closes the browser and then opens it to know where he is working.
two。 Ability to cache data: a lot of data that will not change does not need to be obtained from the server every time.
3. Can save users' preferences: this kind of data usually does not need to exist on the server side.
The previous practice
Before HTML5 local storage, if we want to keep persistent data on the client side, there are several options:
1. HTTP cookie . The disadvantage of HTTP cookie is obvious: at most, you can only store 4KB data, and every HTTP request will be sent back to the server for plaintext transmission (unless you use SSL).
2. IE userData . UserData is a local storage solution launched by Microsoft during the browser war in the 1990s. It uses the behaviour attribute of DHTML to store local data, allowing up to 64K data per page and 640K data per site. The shortcomings of userData are obvious, it is not part of the Web standard, unless your program only needs to support IE, it is basically useless.
3. Flash cookie . Flash cookie is actually not the same thing as HTTP cookie, maybe its name should be called "Flash local storage". Flash cookie allows each site to store no more than 100K of data by default. If it exceeds it, Flash will automatically request more storage space from users. With Flash's ExternalInterface interface, you can easily operate Flash's local storage through Javascript. The problem with Flash is simple because it is Flash.
4. Google Gears . Gears is an open source browser plug-in released by Google in 2007, which aims to improve the compatibility of major browsers. Gears has built-in an embedded SQL database based on SQLite and provides unified API to access the database. After obtaining user authorization, each site can store unlimited size data in the SQL database. The problem with Gears is that Google itself no longer uses it.
The dazzling variety of technologies leads to browser compatibility problems. Cookie is probably the most commonly used here.
New experiences in HTML5
To solve the above problems, HTML5 gives a more ideal solution: if you only need to store data that can be solved simply with key/value pairs, you can use Web Storage.
Compared with Cookie, Web Storage has many advantages, which can be summarized as follows:
1. Larger storage space: each individual storage space under IE8 is 10m. Other browser implementations are slightly different, but they are all much larger than Cookie.
two。 The stored content is not sent to the server: when Cookie is set, the content of Cookie is sent along with the request to the server, which is a waste of bandwidth for locally stored data. On the other hand, the data in Web Storage is only local and does not interact with the server.
3. More rich and easy-to-use interfaces: Web Storage provides a richer set of interfaces to make data manipulation easier.
4. Independent storage space: each domain (including subdomains) has its own storage space, and each storage space is completely independent, so it does not cause data confusion.
Web Storage classification
Web Storage actually consists of two parts: sessionStorage and localStorage.
SessionStorage is used to store data in a session (session) locally, which is accessible only to pages in the same session and is destroyed when the session ends. So sessionStorage is not persistent local storage, just session-level storage.
LocalStorage is used for persistent local storage, and the data will never expire unless it is actively deleted.
Check if Web Storage is supported
Web Storage is supported in all major browsers, but in order to be compatible with older browsers, check to see if this technology is available.
The first way: check whether the browser supports Web Storage by checking whether the Storage object exists:
The code is as follows:
If (typeof (Storage)! = "undefined") {
/ / Yes! LocalStorage and sessionStorage support!
/ / Some code.
} else {
/ / Sorry! No web storage support..
}
The second way is to check their respective objects separately, such as whether localStorage supports:
The code is as follows:
If (typeof (localStorage) = = 'undefined') {
Alert ('Your browser does not support HTML5 localStorage. Try upgrading.')
} else {
/ / Yes! LocalStorage and sessionStorage support!
/ / Some code.
}
Or:
If ('localStorage' in window & & window [' localStorage']! = = null) {
/ / Yes! LocalStorage and sessionStorage support!
/ / Some code.
} else {
Alert ('Your browser does not support HTML5 localStorage. Try upgrading.')
}
Or
If (!! localStorage) {
/ / Yes! LocalStorage and sessionStorage support!
/ / Some code.
} else {
Alert ('Your browser does not support HTML5 localStorage. Try upgrading.')
}
Obviously, the first way is the most direct and the simplest.
The use of Web Storage
Key-value pairs are stored in Web Storage, and browsers store them as strings. Remember to convert them to other formats if necessary.
SessionStorage and localStorage have the same list of members except for different purposes:
The code is as follows:
Key = value: store key-value pairs
SetItem (key, value): store key-value pairs
GetItem (key): fetching key-value pairs
RemoveItem (key): removes all key-value pairs
Clear (): clear all key-value pairs
Length: number of key-value pairs
Here I would like to emphasize that the value type in the setItem (key,value) method can theoretically be any type, but in practice the browser will call the toString method of value to get its string value and store it locally, so if it is a custom type, you need to define your own meaningful toString method. For example, the following example is used with JSON.stringify:
The code is as follows:
Var person = {'name':' rainman', 'age': 24}
LocalStorage.setItem ("me", JSON.stringify (person))
JSON.parse (localStorage.getItem ('me')) .name; / /' rainman'
/ * *
* JSON.stringify to convert JSON data into strings
* JSON.stringify ({'name':' fred', 'age': 24}) / /' {"name": "fred", "age": 24}'
* JSON.stringify (['a', 'baked,' c']); / /'["a", "b", "c"]'
* JSON.parse, anti-solve JSON.stringify
* JSON.parse ('["a", "b", "c"]) / / ["a", "b", "c"]
, /
In addition, when adding key-value pairs, if a large number of key-value pairs are added, it is safer to check for exceptions that exceed the limit:
The code is as follows:
Try {
LocalStorage.setItem (itemId, values.join (';'))
} catch (e) {
If (e = = QUOTA_EXCEEDED_ERR) {
Alert ('Quota supervised')
}
}
The method of Web Storage is very simple. The following example counts the number of clicks on button:
The code is as follows:
Function clickCounter ()
{
If (typeof (Storage)! = "undefined")
{
If (localStorage.clickcount)
{
LocalStorage.clickcount=Number (localStorage.clickcount) + 1
}
Else
{
LocalStorage.clickcount=1
}
Document.getElementById ("result") [xss_clean] = "You have clicked the button" + localStorage.clickcount + "time (s)."
}
Else
{
Document.getElementById ("result") [xss_clean] = "Sorry, your browser does not support web storage..."
}
}
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.