What is the difference between sessionStorage and localStorage
The difference between sessionStorage and localStorage is: 1. localStorage has no expiration time; 2. sessionStorage stores data for a session, and the life cycle is the same as the session. When the user closes the browser, the data will be deleted.
The difference between sessionStorage and localStorage
As we all know, since the emergence of the HTML 5 standard, Localized storage once became a hotly searched keyword. At the beginning of HTML 5, there were two ways of local storage: one was web Storage and the other was web SQL. Since the implementation of web SQL is based on SQLite, it is more inclined to the direction of DataBase, and W3C officially announced in November 2011 that it would no longer maintain the web SQL specification, so its API interface currently does not fall within the scope of HTML 5. Therefore, the HTML 5 local storage we often talk about currently mostly refers to web Storage.
The following is a detailed description and explanation of WebStorage and its two forms.
1. webStorage
webStorage is an important function introduced by HTML5. It is often used in the process of front-end development. It can be used on the client Locally stored data is similar to cookies, but its function is much more powerful than cookies. The size of the cookie is only about 4Kb (different browsers have different sizes), while the size of webStorage is 5MB. The methods provided by its API are as follows:
setItem(key,value) - save data and store information in the form of key-value pairs.
getItem(key)——Get the data and pass in the key value to get the corresponding value.
removeItem(key)——Delete a single data and remove the corresponding information based on the key value.
clear()——Delete all data
key(index)——Get the key of an index
2, localStorage
The life cycle of localStorage is permanent. If you use localStorage to store data, even if you close the browser, the data will not disappear unless you actively delete the data. The method used is as shown above. localStorage has a length attribute, you can check how many records of data it has. The usage is as follows:
var storage = null; if(window.localStorage){ //判断浏览器是否支持localStorage storage = window.localStorage; storage.setItem("name", "Rick"); //调用setItem方法,存储数据 alert(storage.getItem("name")); //调用getItem方法,弹框显示 name 为 Rick storage.removeItem("name"); //调用removeItem方法,移除数据 alert(storage.getItem("name")); //调用getItem方法,弹框显示 name 为 null }
localStorage is simpler than sessionStorage, and there are not many things to pay attention to.
3. sessionStorage
The life cycle of sessionStorage is before the browser is closed. In other words, the data will always exist until the entire browser is closed. sessionStorage also has a length attribute, and its basic judgment and usage are the same as those of localStorage. The following points need to be noted:
Refreshing the page will not eliminate the data
For verification, I prepared two html files, one is index .html and the other is text.html. As for text.html, its origin will be discussed in detail later. The html codes of the two are as follows:
index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Test</title> <script> function submit() { var str = document.getElementById("text").value.trim(); setInfo(str); document.getElementById("text").value = ""; } //储存数据 function setInfo(name) { var storage = window.sessionStorage; storage.setItem('name', name); } //显示数据 function shows() { var storage = window.sessionStorage; var str = "your name is " + storage.getItem("name"); document.getElementById("text").value = str; } </script> </head> <body> <input type="button" value="Login" οnclick="submit()" /> <input type="text" name="text" id="text" /> <input type="button" value="show" οnclick="shows()" /> <a href="text.html" target="_blank">点击打开</a> </body> </html>
The text.html page is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> var storage = window.sessionStorage; alert(storage.getItem("name")); </script> </body> </html>
The result of opening the index.html page is as follows:
When the show button is clicked, "your name is null" is displayed in the input box. At this time, there is no data with the key value "name" stored in sessionStorage. After entering "Rick" in the text, click the login button. When the input box is cleared, the data has been stored in sessionStorage. Then click the show button, and "your name is Rick" will be displayed. At this time, click the browser to refresh the web page, and then click the show button. The input box still displays "your name is Rick"
Only links opened on the current page can be used. Access sessionStorage data;
Remember the text.html page you prepared? It is now its turn to play its role. In order to verify, we follow the above steps and open text.html. The result is as follows:
As you can see, this value is null and the value of "name" cannot be obtained. Now, close this text.html page and open the link by clicking on the index.html page. You can see the following results:
Therefore, you can know that at the current time The link opened on the page can access the data in sessionStorage. Later, after some other tests, I found that after opening the text.html page from index.html, closing index.html and refreshing text.html, the data in sessionStorage can also be accessed. The data in sessionStorage can only be eliminated when index.html and all pages opened from it are closed or the browser is closed directly.
Using window.open to open the page and changing the localtion.href method can obtain the data inside sessionStorage
The above two methods have been tested. And indeed it is. Interested students can actually test the results. I will not summarize the differences between localStorage and sessionStorage.
In short, when using it, pay attention to the points mentioned above, and you can avoid many unnecessary pitfalls when using it.
For more related knowledge, please visit PHP Chinese website! !
The above is the detailed content of What is the difference between sessionStorage and localStorage. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use
