Home >Web Front-end >H5 Tutorial >HTML5 data storage example code

HTML5 data storage example code

零下一度
零下一度Original
2017-04-21 15:55:593137browse

html5Data Storage

##So far, there are many ways to implement client-side storage. The simplest and most compatible solution is cookies, but as a real client-side storage, cookies still exist. Some shortcomings.

##The cookie is sent with the http transaction, so some of it will be wasted The bandwidth used when sending cookies. Contact

In this case, the "web storage"

function, a function to save data locally on the client, is re-provided in HTML5.

It contains two storage types

Both SessionStorage and localStorage support storing 5MB data in the same domain

The difference lies in the data of

SessionStorage For temporary storage (when the user closes the browser --- the data will not exist)

localStorage for permanent storage , when the user closes the browser --- the data will still exist (Unless the user manually clears )

※We can use examples to prove it below※

First create two pages

The page code is as follows:

Index.html->
 
<!DOCTYPE html>
<html>
    <head>
       <meta charset="utf-8" />
       <title></title>
    </head>
    <body>
       <a href="test.html" target="_blank">打开测试页面看一下</a>
       <script type="text/javascript">
           window.onload=function(){
              sessionStorage.setItem("date","今天是2017年2月3号,本少心情不错!")
              localStorage.setItem("localDate","我想讲今天这个种心情永久的保存下来,留下最美好的见证!")
           }
          
       </script>
    </body>
</html>
 
Test.html->
 
<!DOCTYPE html>
<html>
    <head>
       <meta charset="UTF-8">
       <title></title>
    </head>
    <body>
       <script type="text/javascript">
           window.onload=function(){
              alert("临时会话:"+sessionStorage.getItem("date"));
              alert("永久会话:"+localStorage.getItem("localDate"));
           }
       </script>
    </body>
</html>

First open the homepage and take a look ->Click the link

##You can see these effects

##Okay now let’s close the browser Let’s see the effect

First copy the link

We only open this text page now

Now you can see that this temporary session disappears when we close browsing

But the data saved through localstorage

is still there There is

So the data here uses different storage according to the different situations you use

Generally, relatively large image data such as fixed Bese64 will be used to store it in the local session, but it is worth noting that the storage here is also limited to 5MB, and storing it in the form of key-value pairs is not conducive to program expansion, so another storage mechanism for HTML is also provided here

"websql

". There is a database built into HTML5 that can be accessed through SQL language. Just look at the name and you will know that this is

Database local storage function

. This is a real database that can query and add data. , in HTML5, the content that can be stored locally on the client is greatly enriched. Currently, file-type SQL data called "SQLLLIte" that does not need to be stored on the server has been widely used, so this kind of database is also used in HTML5 as a local database. database.

Let’s just use examples to illustrate --- (Because those who have studied databases generally understand that this is local data, which is basically the same as the database we usually install.)

Create a new

WebSQL.html

<!DOCTYPE html>
<html>
    <head>
       <meta charset="UTF-8">
       <title></title>
    </head>
    <body>
       <script type="text/javascript">
           window.onload=function(){
              //打开和创建数据库
              var db;
              //首先判断浏览器是否支持本地数据库
              if(window.openDatabase){
                  //初次打开一个数据库,就会自动创建数据库。任何时间,在该“域”上只能拥有指定数据库的一个版本,因此如果创建了
                  //版本1.0,那么应用程序在没有特定的改变数据库的版本时,将无法打开1.1。
                  //打开和创建数据库,第一参数数据库名,第二个参数版本号,第三个参数为数据库的描述,第四个参数为数据库的大小
                  //该方法返回创建后的数据库访问对象,如果该数据库不存在,则创建该数据库。
                  db=openDatabase("myWBSQL",&#39;1.0&#39;,&#39;这个是描述可以写可以不写&#39;,2*1024*1024);
                  //使用事务来执行处理(一般的学过数据库知道这种处理方式的优点)
                  db.transaction(function(tx){
                     //执行SQL语句---这里创建一个数据库
                     tx.executeSql(&#39;create table if not exists st(id,age,name)&#39;);
                     //添加一条SQL语句
                     //第一个参数为需要执行的SQL语句,第二个参数为SQL语句中用到参数数组
                     //后面两个参数为成功和失败的回调函数
                     tx.executeSql("insert into st(id,age,name)values(?,?,?)",["1","天下第几","毛馨婕"],function(tx,results){
                         //成功之后的回调函数
                         alert("插入语句成功");
                         console.info(results);
                     },function(tx,errmsg){
                         alert("插入语句失败!");
                         console.info(errmsg);
                     })
                  });
              }else{
                  alert("您的浏览器不支持本地数据!")
              }
           }
       </script>
    </body>
</html>


Let’s open the Sogou browser to check it out ->

Check it in the console here

Here we are very You can clearly see that the statement inserted into the local database is exactly the same as what we wrote

So let’s create a new page to see the data in the local data after we close the browser

selectSQL.html 
<!DOCTYPE html>
<html>
    <head>
       <meta charset="UTF-8">
       <title></title>
    </head>
    <body>
       <script type="text/javascript">window.onload = function()
 {
    var db;
    if(window.openDatabase)
 {
       db = openDatabase("myWBSQL", &#39;1.0&#39;, &#39;这个是描述可以写可以不写&#39;, 2 * 1024* 1024);
        db.transaction(function(tx)
 {
           tx.executeSql("select * from st where name=?", ["毛馨婕"],function(tx, results)
 {
              console.info(results);
              alert(results[&#39;rows&#39;][0][&#39;name&#39;]+"---"+results[&#39;rows&#39;][0][&#39;age&#39;]);
           }, function(tx, errmsg)
 {
              console.info(errmsg);
           })
       });
    } else {
       alert("您的浏览器不支持本地数据!")
    }
}</script>
    </body>
</html>

Open the page

You can see in the console

Of course this is very simple, but it is the slow accumulation that allows you to grow step by step. So let’s learn together with everyone

Size

The size of the cookie is limited to 4KB.

Bandwidth

Complex

## Cookies are more troublesome to operate: all information must be spelled into one inside a long string.

For cookiess, in the same site with multiple transactions Staying in touch isn't easy.

The above is the detailed content of HTML5 data storage example code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn