Home > Web Front-end > H5 Tutorial > body text

Analyze the storage function of HTML5 and related operation methods of web SQL_html5 tutorial skills

WBOY
Release: 2016-05-16 15:45:55
Original
1342 people have browsed it

HTML5 introduces two mechanisms, similar to HTTP session cookies, for storing structured data on the client side and overcoming the following shortcomings.

Cookies are included in every HTTP request, causing the transfer of the same data to slow down our web application.

Cookies are included with every HTTP request, resulting in unencrypted data being sent over the internet.

Cookies can only store a limited 4KB of data, which is not enough to store the required data.
The two storage methods are session storage and local storage, which will be used to handle different situations.

Almost all recent browsers support HTML5 storage, including Internet Explorer.

Session Storage
_Session Storage_ is designed for scenarios where users perform a single transaction, but multiple transactions can be performed in different windows at the same time.

Example

For example, if a user purchases a flight ticket in two different windows on the same website. If the website uses cookies to track the tickets a user has purchased, the currently purchased tickets will be "leaked" when going from one window to the other as the user clicks through the page, which could result in the user purchasing two tickets for the same flight without noticed.

HTML5 introduced the sessionStorage attribute. This website can be used to add data to the session storage. The user can still access any page of the same site in the open window holding the session. When the window is closed, the session will also lost.

The following code will set a session variable and then access the variable:

XML/HTML CodeCopy content to clipboard
  1. >
  2. <html>
  3. <body>
  4. <script type="text/ javascript">
  5. if( sessionStorage.hits ){
  6. sessionStorage.hits = Number(sessionStorage.hits) 1;
  7. }else{
  8. sessionStorage.hits = 1;
  9. }
  10. document.write("Total Hits:" sessionStorage.hits);
  11. script>
  12. <p>Refresh the page to increase number of hits. p> 
  13. <p>Close the window and open it again and check the result. p>
  14. body>
  15. html>

Local Storage
_Local Storage_ is designed to be stored across multiple windows and persists on the current session. In particular, web applications may want to store millions of bytes of user data on the client for performance reasons, such as entire documents written by a user or a user's mailbox.

Cookies don't handle this situation very well because they are transmitted with every request.

Example

HTML5 introduced the localStorage attribute, which can be used to access the local storage area of ​​​​the page without time limits. Local storage is available whenever we use this page.

The following code sets a local storage variable that can be accessed every time this page is accessed, even the next time the window is opened:

XML/HTML CodeCopy content to clipboard
  1. >
  2. <html>
  3. <body>
  4. <script type="text/ javascript">
  5. if( localStorage.hits){
  6. localStorage.hits = Number(localStorage.hits) 1;
  7. }else{
  8. localStorage.hits = 1;
  9. }
  10. document.write("Total Hits:" localStorage.hits);
  11. script>
  12. <p>Refresh the page to increase number of hits. p> 
  13. <p>Close the window and open it again and check the result. p>
  14. body>
  15. html>

Easy to learn the above concepts - please practice online.

Delete Web Storage
Storing sensitive data on your local machine can be dangerous and may leave security holes.

_Session Stored Data_ will be deleted by the browser immediately after session termination.

To clear local storage settings, you need to call localStorage.remove('key'); this 'key' is the key corresponding to the value we want to remove. If you want to clear all settings, you need to call the localStorage.clear() method.

The following code will completely clear local storage:

XML/HTML CodeCopy content to clipboard
  1. >  
  2. <html>  
  3. <body>  
  4.   
  5.   <script type="text/javascript">  
  6.     localStorage.clear();   
  7.   
  8.     // Reset number of hits.   
  9.     if( localStorage.hits ){   
  10.        localStorage.hits = Number(localStorage.hits)  1;   
  11.     }else{   
  12.        localStorage.hits = 1;   
  13.     }   
  14.     document.write("Total Hits :"   localStorage.hits );   
  15.   script>  
  16.   <p>Refreshing the page would not to increase hit counter.p>  
  17.   <p>Close the window and open it again and check the result.p>  
  18.   
  19. body>  
  20. html>  

Web SQL 数据库
Web SQL 数据库 API 并不是 HTML5 规范的一部分,但是它是一个独立的规范,引入了一组使用 SQL 操作客户端数据库的 APIs。
核心方法
下面是规范中定义的三个核心方法。也会涵盖在本教程中:

openDatabase:这个方法使用现有的数据库或者新建的数据库创建一个数据库对象。
transaction:这个方法让我们能够控制一个事务,以及基于这种情况执行提交或者回滚。
executeSql:这个方法用于执行实际的 SQL 查询。
开启数据库
如果数据库已经存在,openDatabase 方法负责开启数据库,如果不存在,这个方法会创建它。

使用下面的代码可以创建并开启一个数据库:

JavaScript Code复制内容到剪贴板
  1. var db = openDatabase('mydb''1.0''Test DB', 2 * 1024 * 1024);  

The above method accepts the following five parameters:

Database name
Version number
Description text
Database size
Creation callback
The last and fifth parameter, the creation callback will be called after the database is created. However, even without this feature, the runtime will still create the database and the correct version.

Execute the query
To execute the query, you need to use the database.transaction() function. This function takes one parameter, which is a function responsible for actually executing the query, as shown below:

JavaScript CodeCopy content to clipboard
  1. var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
  2. db.transaction(function (tx) {
  3. tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
  4. });

The above query statement will create a table called LOGS in the 'mydb' database.

Insert operation
To create an entry in the table, we add a simple SQL query to the above example as follows:

JavaScript CodeCopy content to clipboard
  1. var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
  2. db.transaction(function (tx) {
  3. tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
  4. tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
  5. tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
  6. });

You can also pass dynamic values ​​like this when creating an entry:

JavaScript CodeCopy content to clipboard
  1. var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
  2. db.transaction(function (tx) {
  3. tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
  4. tx.executeSql('INSERT INTO LOGS
  5. (id,log) VALUES (?, ?'), [e_id, e_log];
  6. });

Here e_id and e_log are external variables, executeSql will map each entry in the array parameter to "?".

Read operation
To read an already existing record, we can use a callback to capture the result as follows:

JavaScript CodeCopy content to clipboard
  1. var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
  2. db.transaction(function (tx) {
  3. tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
  4. tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
  5. tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
  6. });
  7. db.transaction(function (tx) {
  8. tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
  9. var len = results.rows.length, i;
  10. msg = "

    Found rows: " len "

    "
    ;
  11. document.querySelector('#status').innerHTML = msg;
  12. for (i = 0; i < len; i ){
  13. alert(results.rows.item(i).log);
  14. }
  15. }, null);
  16. });

Final Example
Finally, let’s put this example into a full HTML5 document like this and try running it in Safari:

JavaScript CodeCopy content to clipboard
  1.   
  2.   
  3.   
  4. "text/javascript">   
  5. var db = openDatabase('mydb''1.0''Test DB', 2 * 1024 * 1024);   
  6. var msg;   
  7. db.transaction(function (tx) {   
  8.   tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');   
  9.   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');   
  10.   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');   
  11.   msg = '

    Log message created and row inserted.

    '
    ;   
  12.   document.querySelector('#status').innerHTML =  msg;   
  13. });   
  14.   
  15. db.transaction(function (tx) {   
  16.   tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {   
  17.    var len = results.rows.length, i;   
  18.    msg = "

    Found rows: "   len   "

    "
    ;   
  19.    document.querySelector('#status').innerHTML  =  msg;   
  20.    for (i = 0; i < len; i ){   
  21.      msg = "

    "   results.rows.item(i).log   "

    "
    ;   
  22.      document.querySelector('#status').innerHTML  =  msg;   
  23.    }   
  24.  }, null);   
  25. });   
  26.   
  27.   
  28.   
  29. "status" name="status">Status Message
  
  •   
  •   
  • 在浏览器中这会生成如下所示结果:

    复制代码
    代码如下:

    Log message created and row inserted.

    Found rows: 2

    foobar

    logmsg

    Related labels:
    source:php.cn
    Statement of this Website
    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
    Popular Recommendations
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template