H5 local storage detailed use tutorial (localStorage + JSON data storage application framework)







There are two API s for H5 local storage, one is Web Storage and the other is Web SQL. No matter which one is used, it is based on the JavaScript language. Next, I will teach you how to use H5 local storage. This article is large and there are many JS codes. Please read it patiently.





1, Web Storage tutorial


1. Overview:

For Web Storage, it is actually an evolutionary version of Cookie storage. If people who know about Cookies can use Web Storage almost at a glance, if you have never used Cookies and have never known them, it's OK. After reading this article, you can still easily play with Web Storage. First, to learn Web Storage, you only need to memorize the saying: "two interfaces, four functions".


2. Pithy formula:

(1) Two interfaces: localStorage and sessonStorage

(2) Four functions: setItem, getItem, removeItem and clear


3,localStorage:

(1) Characteristics:

Secure and permanent storage in the domain. That is, all pages from the same domain name in the client or browser can access the localStorage data and the data will be permanently saved unless deleted, but the data between the client or browser is independent.

(2) Four functions:

     A. localStorage.setItem stores data information locally

     B. localStorage.getItem: read the information stored locally

     C. localStorage.removeItem deletes locally stored information

     D. localStorage.clear clears all stored information

    


 4,sessonStorage:

(1) characteristics:

Session control and short-term storage. The session concept is similar to the server-side session concept. Short term saving refers to the automatic elimination of data after the window or browser or client is closed.

(2) four functions:

      A. sessionStorage.setItem stores data information locally

      B. sessionStorage.getItem: read the information stored locally

      C. sessionStorage.removeItem deletes locally stored information

      D. sessionStorage.clear clears all stored information

      


5. Usage of the four functions:

(1) Localstorage.setitem (key name, key value)

A string type data is stored in the local client, where the first parameter "key name" represents the identifier of the data, and the second parameter "key value" is the data itself. For example:

                 localStorage.setItem("coffeeType", "mocha"); / / store the data with the key name coffeetype and the key value Mocha locally
                 localStorage.setItem("coffeePrice", "28"); / / with the previous sentence as a reference, you should understand the meaning of this sentence
     

(2) Localstorage.getitem (key name)

Read the data stored locally, and read the data corresponding to the key name through the key name as a parameter. For example:

                 var data = localStorage.getItem("coffeeType"); / / read the data with the corresponding key name coffeetype

     
(3) Localstorage.removeitem (key name)

Remove the data stored locally, and delete the data corresponding to the key name by using the key name as a parameter. For example:

                 localStorage.removeItem("coffeeType"); / / remove the data with the key name coffeetype from the local storage
     
(4)localStorage.clear()

Remove all data stored locally. For example:

                 localStorage.clear(); / / the saved "coffeePrice/28" key / value pair has also been removed. Goodbye to all local data


     
(5) In addition, the four functions in sessionStorage are basically the same as the function usage of the localStorage class above, and will not be explained in detail.

     


6. Compatibility issues:

Some people will say that local storage is the new expensive of H5, but what about old and old browsers? Instead of using an old browser, or use Cookies instead. Because most of the localStorage is used to store strings, in the view of other compiled languages, storing strings can do something. But in javascript, the old one shines brightly. It can store strings in JSON format to expand the application, and can store information such as class name and variable value, and then use eval() to feel the pleasure of using JS. Since localStorage is used to store strings, Cookies can be used as an alternative in antique browsers to ensure domain security.






2, Web Storage application


1. Basic use:

Let's sort out the above four functions and add a verification code to detect the existence of local data storage.


(localStorage usage test)

<script type="text/javascript">

    localStorage.setItem("coffeeType", "mocha");
    localStorage.setItem("coffeePrice", "28");

    verify();   //Verify local storage
    localStorage.removeItem("coffeeType");
    verify();   //Verify whether coffeeType exists
    localStorage.clear();
    verify();   //Verify whether coffeeType and coffeePrice exist

    //Custom validation function to verify whether the data of coffeeType and coffeePrice exist
    function verify(){
        var type = localStorage.getItem("coffeeType");
        var price = localStorage.getItem("coffeePrice");
        type = type ? type : 'non-existent';
        price = price ? price : 'non-existent';

        alert( "coffeeType: " + type + "\n\n" + "coffeePrice: " + price );
    }
</script>

If the pop-up prompt does not exist after the above code is executed, it means that the localStorage of H5 is not supported locally. DON'T worry about what to do if you DON'T support it. You can write a piece of code for compatible use. Please continue to read.


2. Compatible use:

Before writing the compatible code, let's talk about Web Storage. Of the two classes of Web Storage, we usually use the localStorage class. As for the session, let's leave it to the background. However, the localStorage class cannot be used when it does not support H5. Therefore, we encapsulate the four functions of localStorage to automatically switch to cookie storage when the browser or client is not compatible with localStorage.

First, write a class and function to operate cookies. Keep the names, parameters and functions of the four functions consistent with those of localStorage. As it happens, a cookieStorage code has been written in the fifth edition of the JavaScript authority guide. However, this code has bugs and is slightly inconsistent with localStorage, so I modified it and spent some time building the wheel. The code is as follows:


( cookieStorage.js )

//The book "JavaScript authority guide" has a storage API based on cookie s. I'll type the code down
// In addition, the code in the book is wrong. The following is the BUG free version and modified to 1000 days, which is a long storage time
window.cookieStorage = (new (function(){
    var maxage = 60*60*24*1000;
    var path = '/';

    var cookie = getCookie();

    function getCookie(){
        var cookie = {};
        var all = document.cookie;
        if(all === "")
            return cookie;
        var list = all.split("; ");
        for(var i=0; i < list.length; i++){
            var cookies = list[i];
            var p = cookies.indexOf("=");
            var name = cookies.substring(0,p);
            var value = cookies.substring(p+1);
            value = decodeURIComponent(value);
            cookie[name] = value;
        }
        return cookie;
    }

    var keys = [];
    for(var key in cookie)
        keys.push(key);

    this.length = keys.length;

    this.key = function(n){
        if(n<0 || n >= keys.length)
            return null;
        return keys[n];
    };

    this.setItem = function(key, value){
        if(! (key in cookie)){
            keys.push(key);
            this.length++;
        }

        cookie[key] = value;
        var cookies = key + "=" +encodeURIComponent(value);
        if(maxage)
            cookies += "; max-age=" + maxage;
        if(path)
            cookies += "; path=" + path;

        document.cookie = cookies;
    };

    this.getItem = function(name){
        return cookie[name] || null;
    };

    this.removeItem = function(key){
        if(!(key in cookie))
            return;

        delete cookie[key];

        for(var i=0; i<keys.length; i++){
            if(keys[i] === key){
                keys.splice(i, 1);
                break;
            }
        }
        this.length--;

        document.cookie = key + "=; max-age=0";
    };

    this.clear = function(){
        for(var i=0; i<keys.length; i++)
            document.cookie = keys[i] + "; max-age=0";
        cookie = {};
        keys = [];
        this.length = 0;
    };
})());


With the above cookieStorage function, it's easy to do. Just integrate localStorage and cookieStorage.

Then start, create a myStorage.js file, Copy the cookieStorage code above, and then start writing the following code:


( myStorage.js )

//Local storage: the localStorage class has no storage space limitation, while the cookie storage class has storage size limitation
//If localStorage is not supported, it will be automatically switched to cookieStorage
window.myStorage = (new (function(){

    var storage;    //Declare a variable that determines which local storage function to use

    if(window.localStorage){
        storage = localStorage;     //When localStorage exists, use H5 mode
    }
    else{
        storage = cookieStorage;    //When localStorage does not exist, use compatible mode
    }

    this.setItem = function(key, value){
        storage.setItem(key, value);
    };

    this.getItem = function(name){
        return storage.getItem(name);
    };

    this.removeItem = function(key){
        storage.removeItem(key);
    };

    this.clear = function(){
        storage.clear();
    };
})());


The above code is myStorage.js. You can Copy it directly. After importing the prepared myStorage.js file into the HTML document, the usage is the same as the localStorage function. If you don't believe it, try it:


(1) Mystorage.setitem (key name, key value)

A string type data is stored in the local client, where the first parameter "key name" represents the identifier of the data, and the second parameter "key value" is the data itself. For example:

                 myStorage.setItem("coffeeType", "mocha"); / / store the data with the key name coffeetype and the key value Mocha locally
                 myStorage.setItem("coffeePrice", "28"); / / with the previous sentence as a reference, you should understand the meaning of this sentence
     
(2) Mystorage.getitem (key name)

Read the data stored locally, and read the data corresponding to the key name through the key name as a parameter. For example:

                 var data = myStorage.getItem("coffeeType"); / / read the data with the corresponding key name coffeetype
     
(3) Mystorage.removeitem (key name)

Remove the data stored locally, and delete the data corresponding to the key name by using the key name as a parameter. For example:

                 myStorage.removeItem("coffeeType"); / / remove the data with the key name coffeetype from the local storage
     
(4)myStorage.clear()

Remove all data stored locally. For example:

                 myStorage.clear(); / / the saved "coffeePrice/28" key / value pair has also been removed. Goodbye to all local data


If you take a closer look, you will find that the local in localStorage is changed to my and myStorage is changed. This is amazing. When the customer's use environment does not support H5, this small face change "my" will be switched to cookies, which may save your life. However, in order to save your life, you can create an additional wheel. When the customer environment does not support H5 and cookies, the wheel will automatically upload the data to the server for storage; If the customer supports cookies but has the habit of clearing them regularly, you can make a wheel to control the cookie time, and back up the data to the service within a limited time, and so on. It depends on how you play.


Children's shoes that want to save time can be directly Click nextloadmyStorage.js.


In H5 local storage, in addition to the Web Storage including localStorage and sessionStorage, there is also a niche Web SQL. Please see the following.






3, Web SQL tutorial



1. Overview:

In the local storage of H5, in fact, localStorage is not a very powerful storage, but the Web SQL Database is the most powerful one. A local database application can be directly implemented in the browser or the client, such as making a personal memo. Note that it is a person. Why? Because only mainstream browsers in the world have implemented the WebSQL function, many non mainstream browsers are not compatible with WebSQL, and the so-called mainstream is only the mainstream in the eyes of programming developers. If it is those messy browsers that users usually use, WebSQL is simply a disaster!!! In addition, the support for WebSQL among browsers is not a standard, because this standard was officially abandoned a few years ago. Another reason why WebSQL cannot be widely used is that a large number of front-end engineers do not understand the database, nor do they have the motivation or curiosity or spare time to study and learn to apply WebSQL, which leads to the phenomenon that developers avoid WebSQL, users do not have the habit of using WebSQL, and various clients have uneven compatibility with WebSQL. This is the main reason why WebSQL cannot be widely used as a server-side database.


Roast belongs to roast, and the tutorial should be written. Let's start with the pithy formula: "one language, three functions".



2. Pithy formula:

(1) A language: whether it is WebSQL or MySQL, the syntax of SQL must be mastered. SQL is a structured query language, which is the most natural and concise language used to query data.

(2) The three functions are:
A. openDatabase: create or open a local database object
B. executeSql executes the SQL statement and obtains the execution result in the parameters of the callback function
C. transaction handles transactions. When the execution of a statement fails, all previous executions are invalid


3,SQL:

(1) Overview:

The following is just the most basic SQL statement corresponding to each function. If you don't know SQL, just do simple grammar reference. Those interested in children's shoes need to find information to systematically and comprehensively learn.

(2) Create data table:

Create multiple columns, each of which is used to store different types of data. There is the concept that there are columns and naturally there are rows. A row represents a group of data, and each group of data is a data set of multiple columns corresponding to the row.

CREATE TABLE IF NOT EXISTS table name (column name 1 data type, column name 2 data type, column name N data type)

(3) Query data:

Query the data of a row and a column from a table or query all elements in the table.

SELECT column name 1, column name 2, column name 3 FROM table name WHERE a column name = a value

(4) Insert data:

Insert row data into a table, and each value in the row corresponds to the column name.

INSERT INTO table name (column name 1, column name 2, column name N) VALUES (value 1, value 2, value N)

(5) Update data:

Update the value of a column in a row.

UPDATE table name SET column name 1 = new value, column name 2 = new value, column name N = new value WHERE a column name = a value

(6) Delete data:

Delete a row, otherwise delete all data.

DELETE FROM table name WHERE column name = value



4. Three functions of Web SQL local storage:

(1) openDatabase (database name, database version number, display name, size of data saved in the database, callback function (optional))

However, is it really strange that the version number should be written on the parameters, and what is the display name? However, after the test, I just wrote it this way (please set the size yourself), as follows:

          var db = openDatabase("MyDatabase", "", "My Database", 1024*1024);
     

(2) Executesql (query string, used to replace the parameter of the question mark in the query string, execute the success callback function (optional), and execute the failure callback function (optional))

Parameter 1 is naturally an SQL statement in which value data is available? Replace; The second parameter is in the SQL statement? The corresponding value (much like the preprocessing of PDO). Note that executeSql cannot be used alone. It needs to be used under the transaction function. Examples are as follows:

          executeSql("CREATE TABLE IF NOT EXISTS MyData(name TEXT,message TEXT,time INTEGER)");


(3) Transaction (a method containing transaction content, executing success callback function (optional), executing failure callback function (optional))

The transaction content is composed of one or more executeSql functions. This function is difficult to express in language, so please look at the example:

          db.transaction(function(tx){
             tx.executeSql("CREATE TABLE IF NOT EXISTS MyData(name TEXT,message TEXT,time INTEGER)", [], function(){                         alert("create ok")});
                 tx.executeSql("SELECT * FROM MyData", [], function(){alert("select ok")});
                 tx.executeSql("DROP TABLE IF EXISTS MyData", [], function(){alert("drop ok")});

           });



5. Use of Web SQL:

One of the things that programmers like to do most is to package, encapsulate the code into the way they like, and then when they need to use it, they will thank the encapsulated class or function that year for directly modifying it without re creating the wheel. Therefore, I am no exception, encapsulating the three core functions of openDatabase, executeSql and transaction into a class. Note that this class only implements basic functions, and I did not write a conditional query but directly query all the results. Children's shoes interested in encapsulating Web SQL can study the following code:

(if you are not interested, please ignore and skip to the fourth item: H5 locally stored framework program)


( webSQL.js )

//Callback function, which needs to be assigned as a function and initialized to null
var webSQL_create_handle = null;
var webSQL_insert_handle = null;
var webSQL_update_handle = null;
var webSQL_delete_handle = null;
var webSQL_select_handle = null;
var webSQL_drop_handle = null;

//Connect to database (database name, data size)
function webSQL(database="MyDatabase", datasize=1024*1024){
    this.db = openDatabase(database, "", "My Database", datasize);
}
webSQL.prototype={

    //As the prototype of webSQL
    constructor: webSQL,

    //Create a table. The parameters are table name and column name
    create : function(table, allcol){
        var col = "";
        for(var i=0; i<allcol.length; i++){
            col += allcol[i];

            if(i !== allcol.length-1){
                col += ",";
            }
        }
        var sql = "CREATE TABLE IF NOT EXISTS "+table+"("+col+")";
        this.db.transaction(function(tx){
            tx.executeSql(sql,
                [],
                function(tx,rs){
                    console.log(tx,"Table creation succeeded!");
                    if(webSQL_create_handle && typeof(webSQL_create_handle)=="function"){
                        webSQL_create_handle();
                    }
                },
                function(tx,error){
                    console.log(error,"Failed to create table!");
                }
            );
        });
    },

    //Delete the table. The parameter is the table name
    drop : function(table){
        var sql = "DROP TABLE IF EXISTS "+table;
        this.db.transaction(function(tx){
            tx.executeSql(sql,
                [],
                function(tx,rs){
                    console.log(tx,"Delete table succeeded!");
                    if(webSQL_drop_handle && typeof(webSQL_drop_handle)=="function"){
                        webSQL_drop_handle();
                    }
                },
                function(tx,error){
                    console.log(error,"Failed to delete the table!");
                }
            );
        });
    },

    //Insert data, table name, column name and corresponding column value
    insert : function(tableName, colNameArray, colValueArray){
        var allColName = "";
        var quesMark = "";
        for(var i=0; i<colNameArray.length; i++){
            if(colNameArray[i]){
                allColName += colNameArray[i];
                quesMark += "?";
                if(i !== colNameArray.length-1){
                    allColName += ",";
                    quesMark += ",";
                }
            }
        }
        var sql = "INSERT INTO "+tableName+"("+allColName+") VALUES ("+quesMark+")";
        this.db.transaction(function(tx){
            tx.executeSql(
                sql,
                colValueArray,
                function(tx,rs){
                    console.log(tx,"Data insertion succeeded!");
                    if(webSQL_insert_handle && typeof(webSQL_insert_handle)=="function"){
                        webSQL_insert_handle();
                    }
                },
                function(tx,error){
                    console.log(error,"Failed to insert data!");
                }
            );
        });
    },

    //Update data, table name, column name, column value, conditional column name, conditional column value, conditional relationship, and whether to match
    update : function(tableName, colNameArray, colValueArray, whereColName=null, whereColValue=null, relation="&&", equal="="){
        var colAndValue = "";
        for(var i=0; i<colNameArray.length; i++){
            if(colNameArray[i]){
                colAndValue += (colNameArray[i] + "=?");
                if(i !== colNameArray.length-1){
                    colAndValue += ",";
                }
            }
        }
        var whereSyntax = "";
        if(whereColName){
            for(var j=0; j<whereColName.length; j++){
                if(whereColName[j]){
                    if(j === 0){
                        whereSyntax += " WHERE ";
                    }
                    whereSyntax += (whereColName[j] + "" + equal + "?");
                    if(j !== whereColName.length-1){
                        whereSyntax += (" "+relation+" ");
                    }
                }
            }
        }
        var fanalArray = new Array();
        for(var m=0; m<colValueArray.length; m++){
            if(colValueArray[m]){
                fanalArray.push(colValueArray[m]);
            }
        }
        if(whereColValue){
            for(var n=0; n<whereColValue.length; n++){
                if(whereColValue[n]){
                    fanalArray.push(whereColValue[n]);
                }
            }
        }
        var sql = "UPDATE "+tableName+" SET "+colAndValue+""+whereSyntax;
        this.db.transaction(function(tx){
            tx.executeSql(
                sql,
                fanalArray,
                function(tx,rs){
                    console.log(tx,"Data update succeeded");
                    if(webSQL_update_handle && typeof(webSQL_update_handle)=="function"){
                        webSQL_update_handle();
                    }
                },
                function(tx,error){
                    console.log(error,"Failed to update data!");
                }
            );
        });
    },

    //Delete data, table name, condition column name, condition column value, condition relationship, and whether to match
    delete : function(tableName, whereColName=null, whereColValue=null, relation="&&", equal="="){
        var whereSyntax = "";
        if(whereColName){
            for(var j=0; j<whereColName.length; j++){
                if(whereColName[j]){
                    if(j === 0){
                        whereSyntax += " WHERE ";
                    }
                    whereSyntax += (whereColName[j] + "" + equal + "?");
                    if(j !== whereColName.length-1){
                        whereSyntax += (" "+relation+" ");
                    }
                }
            }
        }
        var fanalColValue = new Array();
        for(var n=0; n<whereColValue.length; n++){
            if(whereColValue[n]){
                fanalColValue.push(whereColValue[n]);
            }
        }
        var sql = "DELETE FROM "+tableName+""+whereSyntax;
        this.db.transaction(function(tx){
            tx.executeSql(
                sql,
                fanalColValue,
                function(tx,rs){
                    console.log(tx,"Data deletion succeeded!");
                    if(webSQL_delete_handle && typeof(webSQL_delete_handle)=="function"){
                        webSQL_delete_handle();
                    }
                },
                function(tx,error){
                    console.log(error,"Failed to delete data!");
                }
            );
        });
    },

    //Query all data
    select : function(tableName){
        var sql = "SELECT * FROM "+tableName;
        console.log("db",this.db);
        this.db.transaction(function(tx){
            tx.executeSql(
                sql,
                [],
                function(tx,rs){
                    for(var i=0; i<rs.rows.length; i++){
                        console.log(rs.rows.item(i).name, rs.rows.item(i).value);
                    }
                    if(webSQL_select_handle && typeof(webSQL_select_handle)=="function"){
                        webSQL_select_handle(rs.rows);
                    }
                },
                function(tx,error){
                    console.log(error,"Query failed");
                }
            );
        });
    }
}


The long code looks very long and smelly. In fact, this class is very easy to use. First, I want to save this class in a JS file. I name it webSQL.js, and then I need to introduce this class into the HTML document for use. The following is how to use this class:


(webSQL.js usage test)

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>test Web SQL database</title>
</head>
<body>
	<div id="msg">
		<b>Test test Web SQL</b><br><br><br>
	</div>
	
<script src="webSQL.js"></script>

<script type="text/javascript">

		//Supplement the callback function after the complete query execution according to the needs. Note that there are parameters, and the parameters are the query results
		webSQL_select_handle = function(rows){
			document.getElementById("msg").innerHTML += "Reading data<br><br>";
			for(var i=0; i<rows.length; i++){
        //Rows is the query result. Row data can be obtained from [rows. Item (data line number)], and column field data in row data can be obtained from [rows. Item (line number). Field name]
				document.getElementById("msg").innerHTML += ((i+1)+". name: "+rows.item(i).name + ", value: " + rows.item(i).value +"<br><br>");
			}
		};

		//Supplement the execution callback function after completing the new data table according to the needs
		webSQL_create_handle = function(){
			document.getElementById("msg").innerHTML += "Creating data table<br><br>";
		};

		//Supplement the execution callback function after complete data insertion according to the needs
		webSQL_insert_handle = function(){
			document.getElementById("msg").innerHTML += "Inserting data<br><br>";
		};

		//Supplement the execution callback function after completely updating the data according to the needs
		webSQL_update_handle = function(){
			document.getElementById("msg").innerHTML += "Updating data<br><br>";
		};

		//Supplement the execution callback function after complete deletion of data according to requirements
		webSQL_delete_handle = function(){
			document.getElementById("msg").innerHTML += "Deleting data<br><br>";
		};

		//Supplement the execution callback function after deleting the table according to the needs
		webSQL_drop_handle = function(){
			document.getElementById("msg").innerHTML += "Emptying and deleting data table<br><br>";
		}

		//Instantiate webSQL class
		var db = new webSQL("MyDatabase");

		//Create a new table with two fields, name and value
		db.create("myTable", ["name", "value"]);

		//Insert two data, Coffe and me
		db.insert("myTable", ["name", "value"], ["Coffee", "me"]);
		
		//Insert two data, JavaScript and good
		db.insert("myTable", ["name", "value"], ["JavaScript", "good"]);

		//Query all data
		db.select("myTable");

		//Update the data and change the value of the name field to Coffee to lhb
		db.update("myTable",["name"],["lhb"],["name"],["Coffee"]);

		//Query all data
		db.select("myTable");

		//Delete the data name d lhb
		db.delete("myTable",["name"],["lhb"]);

		//Query all data
		db.select("myTable");

		//Delete table
		db.drop("myTable");
</script>
</body>
</html>

The usage is very simple, isn't it? Just pass the parameters to the function I wrote. However, this code only passed the test in Chrome Google browser, and other browsers have not tried it. I'm not sure whether it is compatible with other browsers.



If you need the webSQL.js library, you can copy, paste or Click here to download If you need a complete SQL operation, please refer to write or find other class libraries (many great gods on the Internet have encapsulated WebSQL). All the codes in this article are only for learning and reference, and are not suitable for direct production.






4, H5 framework program for local storage (key)



1. Advanced application of localStorage class:

Because not all browsers support WebSQL, and localStorage has the characteristics of unlimited and long-term storage on the hard disk, it can be transformed into an application with database characteristics. If you want localStorage to have the function of database, you can only rely on JSON to achieve great things. JSON is text, language, object and array. As long as it works with JS, it is almost omnipotent (exaggerated)! Since JSON is essentially a string, it is very convenient to store it locally through localStorage. However, JSON can be converted into an object through JS (nowadays almost all languages can parse JSON), so small strings can achieve infinite possibilities. As long as you have imagination, JSON + JavaScript has strong action power.

   

That's too far! Let's talk about how to use JSON first: first, download the json2.js file from the JSON official website and introduce it into HTML; Then use the JSON.stringify(js object) function to convert the JS object into a JSON string, or use the JSON The parse (JSON string) function converts the JSON string into a JS object. Is it abstract? Just look at the code:


(JSON usage method)

<script src="json2.js"></script>
<script type="text/javascript">
    var Obj = { name: 'Coffee', sex: 'man' };   //A js object
    
    var Json = JSON.stringify(Obj);   //Convert js objects to json strings
    
    var Js = JSON.parse(Json);        //json string to js object
</script>


After mastering the basic operation of JSON, we can realize a set of convenient local data storage. Let's analyze it first. We don't need complicated SQL statements to analyze the operations we need to do on the database. We only need to have a set of API s to directly transfer values and call. A database needs to establish a space to store information. Let's first assume that a space can be infinitely expanded and dynamically adjusted, but the values of each space are not related. The concept of this space is similar to the traditional data table.


Therefore, we need a function that mainly manages the space. The main functions of this function are: storing the name of each space, creating a new space, ensuring that the space exists when inserting data into the space, otherwise the insertion fails, and deleting the space at will.

With the concept of space, it is necessary to have a robot that manages the interior of the space. The actions that the robot understands are like basic SQL operations, and have the functions of adding, deleting, querying and modifying.

Space can be understood as a container, which is like an array. However, the members of this array are not of the same type, with various styles, large and small. Here, the concept of members is like objects, and each object can be different.


After having the above ideas, my fingers ran uncontrollably along with the ideas. As a result, I wrote such a JSON based local storage, which is one of the most satisfied Codes:


( localDB.js )

//The myStorage.js file is required
//The json2.js file is required
if(! (myStorage && JSON)){
    alert("need myStorage.js and json2.js Two files");
}

window.localDB = (new (function(){

    //Create a space, the parameter is the space name
    this.createSpace = function(space_name){

        if( typeof(space_name)!=="string" ){
            console.log("space_name The parameter needs to be a string");
            return false;
        }
        //If there is no DBSPACE manager, create a new one; otherwise, check whether a space with the same name already exists in the space manager
        if(!myStorage.getItem("localSpaceDB")){
            var space_obj = [];
            var space_json = JSON.stringify(space_obj);     //Convert object to JSON format
            myStorage.setItem("localSpaceDB", space_json);

            console.log("newly build localSpaceDB success");
        }

        //Take out all the space names. The space names exist in JSON, so they need to be converted into JS objects
        var space_obj = JSON.parse(myStorage.getItem("localSpaceDB"));

        //Check whether the object has a space name
        for(var i=0; i<space_obj.length; i++){
            if(space_obj[i].spaceName == space_name){

                console.log("Space name already exists"+space_name+",New failed");

                return false;   //If the space name already exists, exit the function and return the failure value
            }
        }

        //The space manager localSpaceDB registers a new space
        var new_obj = {     //Save the space name in the new object
            spaceName : space_name
        };
        var old_space_obj = JSON.parse(myStorage.getItem("localSpaceDB"));   //Gets the object that stores all space names
        old_space_obj.push( new_obj );
        var new_space_json = JSON.stringify(old_space_obj);
        myStorage.setItem("localSpaceDB", new_space_json);

        //Create a new variable named space_ Space for the value of name
        var data_obj = [];
        var data_json = JSON.stringify(data_obj);
        myStorage.setItem(space_name, data_json);

        console.log("newly build"+space_name+"Space success");
        return true;
    };


    //Delete a space, and the parameter is the space name
    this.deleteSpace = function(space_name){
        if( typeof(space_name)!=="string" ){
            console.log("space_name The parameter needs to be a string");
            return false;
        }
        //Basis variable for determining whether to delete
        var isDelete = false;
        //Space manager: subscript of the space name to be deleted
        var delIndex = -1;
        //Is there a space manager (localSpaceDB)
        if(myStorage.getItem("localSpaceDB")){
            //Get the json data of all space names in the space manager and convert them into js objects
            var all_space_name_obj = JSON.parse(myStorage.getItem("localSpaceDB"));
            //Detect the presence of space_ Space name of name value, record deletion information
            for(var i=0; i<all_space_name_obj.length; i++){
                if(all_space_name_obj[i].spaceName == space_name){
                    isDelete = true;
                    delIndex = i;
                }
            }
            //Determine whether to delete
            if(isDelete === true && delIndex !== -1){
                all_space_name_obj.splice(delIndex, 1);     //Delete space name
                var new_space_json = JSON.stringify(all_space_name_obj);    //Convert object to JSON
                //Update space manager information
                myStorage.setItem("localSpaceDB", new_space_json);
                //Delete space
                myStorage.removeItem(space_name);

                console.log("Successfully deleted"+space_name+"space");
                return true;
            }
            else{
                console.log("Failed to delete space, it does not exist"+space_name+"space");
                return false;
            }
        }
    };

    //Insert data. The parameters are the space name and the inserted object (not only expressed by value, but also expressed by object)
    this.insert = function(space_name, obj_data){
        //Detect the presence of space
        if(myStorage.getItem(space_name)){
            //Get data stored in space
            var all_data = JSON.parse(myStorage.getItem(space_name));
            //insert data
            all_data.push(obj_data);
            myStorage.setItem(space_name, JSON.stringify(all_data));

            console.log("Inserted data:"+obj_data+",All data are as follows:");
            console.dir(all_data);
            return true;
        }
        else{
            console.log("non-existent"+space_name+"space");
            return false;
        }
    };

    //Update data, the parameter is the old object and the new object used to replace the existing object
    //If there are identical data in the space, update the latest one
    this.update = function(space_name, obj_origin, obj_replace){
        //Detect the presence of space
        if(myStorage.getItem(space_name)){
            //Get old object subscript
            var objIndex = -1;
            //Get data stored in space
            var all_data = JSON.parse(myStorage.getItem(space_name));
            //Traverse the space and find obj_origin object
            for(var i=all_data.length-1; i>=0; i--){
                //If an old object is found
                if(JSON.stringify(all_data[i]) == JSON.stringify(obj_origin)){
                    objIndex = i;
                }
            }
            //If an old object is found
            if(objIndex !== -1){
                all_data.splice(objIndex, 1, obj_replace);
                //Update space
                myStorage.setItem(space_name, JSON.stringify(all_data));

                console.log("Updated data:"+obj_origin+",All data are as follows:");
                console.dir(all_data);
                return true;
            }
            else{
                console.log("No,"+obj_origin+"object");
                return false;
            }
        }
        else{
            console.log("non-existent"+space_name+"space");
            return false;
        }
    };

    //Delete data. The parameter is the object to be deleted
    //If there are identical data in the space, delete the latest one
    this.delete = function(space_name, obj_data){
        //Detect the presence of space
        if(myStorage.getItem(space_name)){
            //Get old object subscript
            var objIndex = -1;
            //Get data stored in space
            var all_data = JSON.parse(myStorage.getItem(space_name));
            //Traverse the space and find obj_data object
            for(var i=all_data.length-1; i>=0; i--){
                //If an old object is found
                if(JSON.stringify(all_data[i]) == JSON.stringify(obj_data)){
                    objIndex = i;
                }
            }
            //If an old object is found
            if(objIndex !== -1){
                all_data.splice(objIndex, 1);
                //Update space
                myStorage.setItem(space_name, JSON.stringify(all_data));

                console.log("Deleted data:"+obj_data+",All data are as follows:");
                console.dir(all_data);
                return true;
            }
            else{
                console.log("No,"+obj_data+"object");
                return false;
            }
        }
        else{
            console.log("non-existent"+space_name+"space");
            return false;
        }
    };

    //Query function, the parameter is string or number or array or boolean, or the property of object, and returns a result array
    this.select = function(space_name, select_value=" ", is_select_all=true){
        if(myStorage.getItem(space_name)){
            //Initialize result array
            var select_result = [];

            //Produce objects stored in the result array
            function productObj(row, ob){
                return ({
                    At : row,
                    Obj : ob
                });
            };

            //Get space_ All data objects in the name space
            var all_data = JSON.parse(myStorage.getItem(space_name));

            //If query criteria exist:
            if(select_value){
                //Find all
                if(is_select_all === true){
                    for(var i=all_data.length-1; i>=0; i--){
                        //Find all, generate result set
                        select_result.push(new productObj(i,all_data[i]));
                    }
                }
                else{
                    //Condition search
                    for(var i=all_data.length-1; i>=0; i--){
                        //If the format is the same, the detection value is equal
                        if( typeof(all_data[i]) === typeof(select_value) ){
                            if(JSON.stringify(all_data[i]) === JSON.stringify(select_value) ){
                                //If found, save to result set
                                select_result.push(new productObj(i,all_data[i]));
                            }
                        }
                        else{
                            if( typeof(all_data[i]) !== "number" ||
                                typeof(all_data[i]) !== "boolean" ||
                                typeof(all_data[i]) !== "string"
                            ){
                                for( var x in all_data[i]){
                                    if(typeof(all_data[i][x]) === typeof(select_value)){
                                        if(JSON.stringify(all_data[i][x]) === JSON.stringify(select_value) ){
                                            //If found, save to result set
                                            select_result.push(new productObj(i,all_data[i]));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if(select_result.length>0){
                console.log("Query results");
                console.dir(select_result);
            }
            else{
                console.log("No results found");
            }

            //Return result set
            return select_result;
        }
        else{
            console.log("non-existent"+space_name+"space");
            return [];
        }
    };

})());

As for the usage of localDB.js above, it is very simple. I wrote an example:


(localDB.js usage test)

<script src="myStorage.js"></script>
<script src="json2.js"></script>
<script src="localDB.js"></script>

<script type="text/javascript">

    //Create a storage space called Coffee
    localDB.createSpace("Coffee");

    //You can insert any type of data into Coffee
    localDB.insert("Coffee", "mocha");
    localDB.insert("Coffee", {name:"cappuccino",price:28});
    localDB.insert("Coffee", false);
    localDB.insert("Coffee", [1,2,3]);

    //When updating some data, the second parameter needs to be the same as the value of the corresponding parameter when inserting
    localDB.update("Coffee", "mocha", "DB");
    localDB.update("Coffee", {name:"cappuccino",price:28}, {name:"latte",price:31})

    //Query the data by conditions and return the result array. At most, the third layer of data in the space can be deeply mined by conditions. Children's shoes interested can add a recursion to keep it mining data
    var some = localDB.select("Coffee","man");
    //If the second and third parameters are not entered, all data in the space will be searched
    var all = localDB.select("Coffee");

    //Delete the data in the space. The second parameter needs to be the same as the corresponding parameter value when inserting
    localDB.delete("Coffee","DB");
    //Delete the coffee space, and all data in the space will be lost
    localDB.deleteSpace("Coffee");
    
</script>


2. Related concepts of localDB data storage:

(1) Two spaces:

The space here refers to the functions of the space manager. One is the createSpace function, which is used to create a storage space by name, and the other is the deleteSpace function, which is used to delete a storage space by name.

(2) Four operations:

The operations here refer to the operations that can be performed on a space. The first is that the insert operation can insert any type of data into the space, the second is that the update operation can replace a data in the space with a data, and the third is that the delete operation can delete a data in the space, The fourth is that the select operation can query the matching data in the space according to one data and return a result array storing multiple {At: result array subscript value, Obj: result object} objects.


(3) Comparison:

Is it much simpler than WebSQL? Originally, I intended to encapsulate local as a database operated by SQL, but there are three reasons to stop my impulse. First, I have no time (it took me several days to complete this article); Second, there are already great gods on the Internet. I think it's unnecessary to encapsulate them again because of the complexity; Third, even if the operation of turning localDB into SQL is not as good as using WebSQL directly. If we exclude the inertia of using the database before, from the perspective of JS, the use of WebSQL completely loses the biggest feature of JS - dynamic. Choosing JSON instead of using the SQL solution conforms to the orthodox blood of JS. As long as we do not consider the performance problem and minimize the impact of performance, the H5 local storage based on JSON is suitable for the front-end environment. JS+JSON can give birth to more creative programming methods, At the same time, H5 will become more and more attractive and challenging.


3. Application scenario of localDB class:

What can I do with the localDB class? There are many things to do. For example, saving the user's account, password and account information locally can avoid the second login of the same website, or avoid increasing the burden of the server caused by repeated requests for data. The local and server data can be synchronized regularly according to the serial number or md5 value and other schemes. In short, in the field of H5 local storage, native localStorage is the most widely used. As for seesionStorage, it is not as convenient and practical as the server-side language. It is needless to say that webSQL has poor compatibility, is too cumbersome to develop, and is a bit weak. Therefore, if you want to experience or use H5 storage, you can try my localDB. The purpose is to provide you with some ideas by using the localDB I wrote, and then you can create your own H5 local storage function according to your needs.


For children's shoes that need localDB.js, please Click here to download.







5, Summary;


If it is a website, most of them still rely on the server. Almost all the data are stored in the server, and a large number of numerical operations are also stored in the server. Therefore, for the website, H5 local storage, in addition to improving the user experience and strengthening the local application functions, seems to be a bit awkward. However, H5 is not all used for websites. For example, in terms of games, H5 local storage provides a good storage function, which means that what H5 does is not necessarily a networked application. It can also be a local application. It can play without a network. In the absence of a network, local storage is a necessary existence. While the development of NativeApp tends to be heavily networked applications, WebApp is quietly taking into account and improving its local use. It is hard to say who will replace it in the future. However, the development trend is that native software is more dependent on hardware support, that is, software hardware, while H5 technology products are used anytime and anywhere.










Tags: Javascript html5 cookie localStorage

Posted by bweekly on Mon, 22 Aug 2022 03:29:35 +0300