Database of H5 Caches

Source: Internet
Author: User
Tags sessionstorage

/*======================================================= function: Save log to local database ===================================== ==================*/function Savelog (str) {var db= Window.opendatabase ("Web", "1.1", "Log", 1024 * 1024); //failed to create or open database    if(!DB) {return; } //Create a tabledb.transaction (Function (TX) {Tx.executesql ("CREATE TABLE if not exists log (createtime text, content text)");    }); //Inserting Recordsdb.transaction (Function (TX) {Tx.executesql (INSERT into log (createtime, content) VALUES (?,?) ", [NewDate (). Format ("YyyyMMdd hh:mm:ss"), Str],NULL,NULL); });}/*======================================================= function: Query the local database for log information ================================== =====================*/function Selectlog (SQL) {var db= Window.opendatabase ("Web", "1.1", "Log", 1024 * 1024); //failed to create or open database    if(!DB) {return; } //Querying Datadb.transaction (Function (TX) {if(sql = = undefined | | sql = = "") {sql = "select * FROM Log"; } Tx.executesql (sql, [], function (TX, result) { for(var i = 0; i < result.rows.length; i++) {Console.warn (Result.rows.item (i) [' Content ']); }}, function () {Console.error ("The query failed!" Reason: 1, no table created; 2. No data in the table ");    }); });}/*======================================================= function: Emptying database table Data ======================================= ================*/function Clearlog () {var db= Window.opendatabase ("Web", "1.1", "Log", 1024 * 1024); //failed to create or open database    if(!DB) {return; } Db.transaction (Function (TX) {Tx.executesql ("DROP TABLE Log"); });}

1. Requirements background: When the user adds a row of data on the page, suddenly found that the network is broken, the page editing data can not be saved into the database, so need a local side of the temporary save function, in order to re-load after the network unblocked!

2. Solution:

The combination of online searching, considering the following ways: 1) using cookies; 2) See if you can use the browser's page cache to simulate 3) using HTML5

1) cookie use (do test is directly with the browser open no effect, need to put into the site)

All browsers are supported, so there is no need to consider compatibility issues;

The browser supports up to 20 cookies for the same domain, and the length of each cookie is limited, and the extra-long section is truncated

Expiration limit: Valid for the lifetime of the cookie and will be cleared out after expiration

There is a request for the server every time the cookie will be attached to increase the network bandwidth

In view of the above considerations, and the project would like to be stored in file form, not to consider!

Examples of cookie storage operations:

12345678910111213141516171819202122232425 function setCookie() {    var value = $(‘#data‘).val();    if (value != ‘‘ && $.trim(value) != ‘‘) {        var expireDate = new Date();        expireDate.setTime(expireDate.getTime() + 30 * 24 * 3600 * 1000);        document.cookie = "data=" + escape(value) + ("; expires=" + expireDate.toGMTString());           } else {        alert(‘请输入要存储的数据!‘);    }}function getCookie() {    if (document.cookie.length > 0) {        var startIndex = 5;        var endIndex = document.cookie.indexOf(";", 0);        var data = "";        if (endIndex != -1) {            data = unescape(document.cookie.substring(startIndex, endIndex));                    } else {            data = unescape(document.cookie.substring(startIndex, document.cookie.length));        }        $(‘#data-display‘).html(data);    }}

2). Localstorage

HTML5 local storage is divided into two kinds, one is the form of Key-value to store, one is datebase storage;

1.key-value local storage with sessionstorage and localstorage two kinds

Sessionstorage: Session storage, life from the time you enter the site, from the end of the site after closing

Localstorage: Local storage, even if you close the browser, again open the same can read to the stored data, which is the difference between the Sessionstorage

Example:

12 window.localStorage.setItem(‘name‘,‘istone‘);window.localStorage.getItem(‘name‘);

2.HTML5 Local database, provides a set of APIs to operate

1234567891011121314151617181920212223 var db = openDatabase(‘mydb‘, ‘1.0‘, ‘Test DB‘, 2 * 1024 * 1024);        var msg;                   db.transaction(function (tx) {           tx.executeSql(‘CREATE TABLE IF NOT EXISTS LOGS (id unique, log)‘);           tx.executeSql(‘INSERT INTO LOGS (id, log) VALUES (1, "foobar")‘);           tx.executeSql(‘INSERT INTO LOGS (id, log) VALUES (2, "logmsg")‘);           msg = ‘<p>Log message created and row inserted.</p>‘;           document.querySelector(‘#status‘).innerHTML =  msg;        });        db.transaction(function (tx) {           tx.executeSql(‘SELECT * FROM LOGS‘, [], function (tx, results) {              var len = results.rows.length, i;              msg = "<p>Found rows: " + len + "</p>";              document.querySelector(‘#status‘).innerHTML +=  msg;                                 for (i = 0; i < len; i++){                 msg = "<p><b>" + results.rows.item(i).log + "</b></p>";                 document.querySelector(‘#status‘).innerHTML +=  msg;              }           }, null);        });

Browser support Scenarios

3) H5file API

For the preservation of the page data, the use of JS library data JSON, such as: json.stringify (), IE data saved online search is called the browser ' Save as ' function to save to TXT, And for the chrome data save call HTML5 API Interface BLOB package data supplied to the a tag href, file name provided to download

+ View Code

For the local file read, using HTML5 Fileapi:filereader, through the Readastext method read to the local JSON string, Json.parser () to go back.

Database of H5 Caches

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.