Daily Reflections (2020/03/08)

Topic Overview

  • Understanding of the HTML5 webSQL and the IndexedDB
  • How to center a div? How to center a floating element? How to absolutely positioned div centered?
  • Write a method to get the image's original width and height

Subject to answer

Understanding of the HTML5 webSQL and the IndexedDB

  • WebSQL

    • Is an independent front-end module, a web storage, we will often see when debugging, but rarely use. In addition, Google is currently only support, ie Firefox and do not support.

    • Main methods:

      1. openDatabase (database name, version number, description text, database size, create a callback): This method creates a database object using an existing database or create a new database.
      2. Transaction : This method allows us to control a transaction, and based on this case commit or rollback. Perform database operations, the operation content is the normal CRUD database
      3. executeSql (SQL statement, statement of variables, the callback after execution): This method is used to perform the actual SQL query.
      var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
      db.transaction(function (tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
        tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "菜鸟教程")');
        tx.executeSql('INSERT INTO LOGS (id,log) VALUES (?, ?)', [e_id, e_log]); //使用外部变量,执行时会将变量数组中的值依次替换前边的问号位置
          tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { 
              var len = results.rows.length, i; msg = "<p>查询记录条数: " + 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); //查询和回调
        tx.executeSql('DELETE FROM LOGS  WHERE id=1'); //删除
        tx.executeSql('DELETE FROM LOGS WHERE id=?', [id]);
        tx.executeSql('UPDATE LOGS SET log=\'www.w3cschool.cc\' WHERE id=2'); //更新
        tx.executeSql('UPDATE LOGS SET log=\'www.w3cschool.cc\' WHERE id=?', [id]);
      });
    • The final destination of the data, I do understand the role of business is just to run a stored cache of temporary storage and large sites, the page refreshes the library would not exist. The concept itself is quite similar to relational databases

  • IndexedDB

    • With the browser capabilities growing, more and more sites began to consider the large amount of data stored on the client side, thus reducing the acquired data from the server to retrieve data directly from the local. Data storage conventional browser program, not suitable for storing large amounts of data: Cookie size of not more than 4KB, and each request back to the server; the LocalStorage between 2.5MB to 10MB (various different browsers), and does not provide search function, can not create a custom index. Therefore, the need for a new solution, which is the background of the birth IndexedDB. IndexedDB is a local database provided by the browser, allows storing large amounts of data, providing an interface to find, but also indexed. These are LocalStorage not available. In terms of the type of database, IndexedDB does not belong to relational databases (SQL queries are not supported), closer to NoSQL database

    • IndexedDB has the following characteristics:

      (1) stored key-value pair. IndexedDB using internal object repository (object store) store data. All types of data can be directly stored, including JavaScript objects. Object repository, the data in the form "key to" save, each data record has a corresponding primary key, the primary key is unique and can not be duplicated, otherwise it will throw an error.

      (2) Asynchronous. IndexedDB not locked when operating the browser, the user can still perform other operations, which in contrast to the LocalStorage, the latter operation is synchronous. Asynchronous designed to prevent reading and writing large amounts of data, slowing down the performance of the web page.

      (3) support transactions. IndexedDB support transactions (transaction), this means that in a series of steps, as long as the step fails, the entire transaction will have been removed, the database is rolled back to the state before the transaction occurs, there is no case of rewriting only part of the data.

      (4) homologous to limit IndexedDB by homologous restriction, each corresponding to a database to create its domain name. Web page can only access the database under its own domain name, but can not access the cross-domain database.

      (5) Storage space storage space than large IndexedDB LocalStorage much, in general less than 250MB, or even no upper limit.

      (6) support binary storage. IndexedDB can store not only the string, binary data can also be stored (an ArrayBuffer Blob object and objects)

    • IndexedDB some of the basic concepts:

      • Database: IDBDatabase object database is a container for a series of related data. Each domain name (strictly speaking, is a protocol + domain name + port) can be any number of new databases. IndexedDB the concept version of the database. The same time, only one version of the database exists. If you want to modify the database structure (add or delete tables, indexes or primary keys), can only be done by upgrading database versions
      • Object Repository: IDBObjectStore objects, each database contains several objects warehouse (object store). It is similar to a relational database table
      • Index: IDBIndex objects
      • Services: IDBTransaction objects, data read and write and record deletion, the transaction should be completed by. Providing transaction object error, abortand completethree events to monitor operating results
      • Operation request: IDBRequest Object
      • Pointer: IDBCursor objects
      • Primary key collection: IDBKeyRange objects, object repository is stored data records. Each record is analogous to a relational database, but only the two portions of the main data and the key body. It may be a primary key attribute of a data record which can be specified as an integer number incremented
    • Basic Operations

      • (1) Open the database

        The first step is to open a database using IndexedDB, use indexedDB.open()the method.

        This method takes two parameters, the first parameter is a string that represents the name of the database. If the specified database does not exist, it will create a new database. The second parameter is an integer representing the version of the database. If omitted, open an existing database, the default is the current version; When creating a new database, by default 1.

        indexedDB.open()IDBRequest method returns an object. The objects three events error, , success, upgradeneededhandle open operating results database

        (2) New Database

        var db;
        var objectStore;
        var request = window.indexedDB.open(databaseName, version);
        
        request.onerror = function (event) {}
        request.onsuccess = function (event) {
            db = request.result//可以拿到数据库对象
        }
        //如果指定的版本号,大于数据库的实际版本号,就会发生数据库升级事件upgradeneeded
        request.onupgradeneeded = function (event) {
            db = event.target.result;
            if (!db.objectStoreNames.contains('person')) {//判断是否存在
                objectStore = db.createObjectStore('person', { keyPath: 'id' });
        //自动生成主键db.createObjectStore(
        //  'person',
        //  { autoIncrement: true }
        //);
            }
            //新建索引,参数索引名称、索引所在的属性、配置对象
            objectStore.createIndex('email', 'email', { unique: true });
        }

        (3) New data

        Based on the above operation, the need to create a transaction. Table name must be specified and the operation mode ( "read only" or "read-write") when new. After the New Transaction, by IDBTransaction.objectStore(name)way get IDBObjectStore objects, and through the table object add()method, write a record to the table.

        Write operation is an asynchronous operation, by listening connection object successevents and errorevents to see if the write succeeds.

        eg:

        function add() {
          var request = db.transaction(['person'], 'readwrite')
            .objectStore('person')
            .add({ id: 1, name: '张三', age: 24, email: '[email protected]' });
        
          request.onsuccess = function (event) {
            console.log('数据写入成功');
          };
        
          request.onerror = function (event) {
            console.log('数据写入失败');
          }
        }
        
        add();

        (4) read data

        function read() {
           var transaction = db.transaction(['person']);
           var objectStore = transaction.objectStore('person');
           var request = objectStore.get(1);
        
           request.onerror = function(event) {
             console.log('事务失败');
           };
        
           request.onsuccess = function( event) {
              if (request.result) {
                console.log('Name: ' + request.result.name);
                console.log('Age: ' + request.result.age);
                console.log('Email: ' + request.result.email);
              } else {
                console.log('未获得数据记录');
              }
           };
        }
        
        read();

        (5) through the data: All data is recorded traversing table, a pointer to the object IDBCursor. openCursor()The method is an asynchronous operation, so to monitor successevents

        function readAll() {
          var objectStore = db.transaction('person').objectStore('person');
        
           objectStore.openCursor().onsuccess = function (event) {
             var cursor = event.target.result;
        
             if (cursor) {
               console.log('Id: ' + cursor.key);
               console.log('Name: ' + cursor.value.name);
               console.log('Age: ' + cursor.value.age);
               console.log('Email: ' + cursor.value.email);
               cursor.continue();
            } else {
              console.log('没有更多数据了!');
            }
          };
        }
        
        readAll();

        (6) Data Update: IDBObject.put()Method.

        function update() {
          var request = db.transaction(['person'], 'readwrite')
            .objectStore('person')
            .put({ id: 1, name: '李四', age: 35, email: '[email protected]' });
        
          request.onsuccess = function (event) {
            console.log('数据更新成功');
          };
        
          request.onerror = function (event) {
            console.log('数据更新失败');
          }
        }
        
        update();

        (7) Delete data: IDBObjectStore.delete()a method for deleting records

        function remove() {
          var request = db.transaction(['person'], 'readwrite')
            .objectStore('person')
            .delete(1);
        
          request.onsuccess = function (event) {
            console.log('数据删除成功');
          };
        }
        
        remove();

        (8) using an index: the index after adding an index can be used to query data

        var transaction = db.transaction(['person'], 'readonly');
        var store = transaction.objectStore('person');
        var index = store.index('name');
        var request = index.get('李四');
        
        request.onsuccess = function (e) {
          var result = e.target.result;
          if (result) {
            // ...
          } else {
            // ...
          }
        }

How to center a div? How to center a floating element? How to absolutely positioned div centered?

  • div Center:margin:0 auto;
  • Float center (div center can also be used):margin-left: 50%; transform: translate(-50%);
  • Absolute positioning div Center:{ top:0; left:0; bottom:0; right:0; margin: auto; }

Write a method to get the image's original width and height

function loadImageAsync(url) {
    return new Promise(function(resolve, reject) {
        var image = new Image();

        image.onload = function() {
            var obj = {
                w: image.naturalWidth,
                h: image.naturalHeight
            }
            resolve(obj);
        };

        image.onerror = function() {
            reject(new Error('Could not load image at ' + url));
        };
        image.src = url;
    });
}

Guess you like

Origin www.cnblogs.com/EricZLin/p/12446076.html