今天在學習《高級JS編程》,看到離線存儲,cookie和session都十分的熟悉,可是書中還提到了indexedDB和webSQL(已廢棄),indexedDB能夠像mysql同樣建表,這就頗有趣了,能夠把後臺獲取來的數據統一放到indexedDB裏面,那麼即便斷開鏈接,也能實現離線預覽的功能啊,對於indexedDB的內容,這位博主的博客寫的十分的詳細,強烈推薦:https://www.cnblogs.com/dolphinX/p/3415761.htmlphp
好了,言歸正傳,開始咱們的離線預覽之旅吧:html
1.準備一張sql的表,我創建了一個名爲user的表,以下:mysql
咱們如今要作的功能是查找表裏帶id字段的內容而後存到indexedDB裏面,再從indexDB裏面進行取值jquery
2.ajax進行取值運算:es6
html代碼:web
let arr = []; /****ajax獲取mysql數據庫****/ function result() { function Submit(url) { const Promises = new Promise(function (resolve, reject) { const handler = function () { if (this.readyState !== 4) { return; } if (this.status === 200) { resolve(this.response); } else { reject(new Error(this.statusText)); } }; const xrh = new XMLHttpRequest(); let formData = new FormData(); formData.append("id", "id"); xrh.onload = handler; xrh.open("post", url); xrh.responseType = "json"; xrh.send(formData); }); return Promises; } Submit("./select.php").then( function (data) { for (let i in data) { arr.push(eval("(" + data[i] + ")")) } }, function (error) { console.log("錯誤爲:", error) } ) }; result();
如上,樓主習慣使用es6的語法,因此看不懂的童鞋能夠先去看一下es6,阮一峯的《ECMAscript6入門》特別詳細,奉上鍊接:http://es6.ruanyifeng.com/#docs/intro;若是你不想使用es6的promise語法,那麼你能夠使用$.ajax來獲取,都是同樣的。看上面代碼,咱們首先定義一個空數組,而後把獲取來的內容push到數組裏面,千萬不要忘記了eval轉換類型,由於後臺返回的都是字符串類型ajax
3.php進行sql查詢:sql
php代碼以下數據庫
function postData($key,$default = ""){ return trim(isset($_REQUEST[$key])?$_REQUEST[$key]:$default); } $id = postData("id"); $conn = mysqli_connect("localhost", "root", "", "test") or die("鏈接失敗"); $conn->query("set names utf8"); $sql = "select * from user where ".$id." is not null"; $result = $conn->query($sql); $arr = array(); while ($row = $result->fetch_assoc()) { array_push($arr,json_encode($row)); } print_r(json_encode($arr)); $conn->close();
一樣把表裏面查詢到的數據轉換成json格式,而後放到一個數組裏面,那麼咱們來看一下arr數組裏面如今又什麼東西吧:編程
所有獲得了,那麼下一步咱們把這些數據保存到indexedDB裏面,代碼以下:
let myDB = { name: "test", version: 1, db: null }; /***本地存儲數據庫的方法***/ function indexedDB(user) { /**建立數據庫**/ function openDB(name) { let version = 1; let request = window.indexedDB.open(name, version); request.onerror = function (e) { console.log(e.currentTarget.error.message); }; request.onsuccess = function (e) { myDB.db = e.target.result; }; request.onupgradeneeded = function (e) { let db = e.target.result; if (!db.objectStoreNames.contains("students")) { db.createObjectStore("students", {keyPath: "id"}); } console.log('DB version changed to ' + version); }; } let students = user; /*向數據庫裏面添加數據*/ function addData(db, storeName) { let transaction = db.transaction(storeName, 'readwrite'); let store = transaction.objectStore(storeName); for (let i = 0; i < students.length; i++) { store.add(students[i]); } } openDB(myDB.name); setTimeout(function () { addData(myDB.db, "students"); }, 1000); } /*執行查詢的方法*/ indexedDB(arr);
看這段代碼以前必定要先去了解indexedDB,否則都是徒勞的,上面的博主裏面的文章裏面已經闡述的很詳細了,再也不多說,這個時候咱們在indexedDB裏面已經建立了一個test的庫,庫裏面有一個students的表,表的key是id,以下:
那麼咱們在indexedDB裏面有了值,下一步就是取值了,我想點擊button的時候在div裏面顯示id爲1的值,好,代碼以下:
html結構:
<p>從本地數據庫裏面讀取的內容</p> <div> </div> <button>讀取內容觸發器</button>
js代碼:
/**本地數據庫的查詢**/ function getDataByKey(db, storeName, value, cb) { let transaction = db.transaction(storeName, 'readwrite'); let store = transaction.objectStore(storeName); let request = store.get(value); request.onsuccess = cb; } $("button").click(() => { getDataByKey(myDB.db, "students", "1", function (e) { let text = e.target.result; let content = ""; for (let i in text) { content += `${i}爲${text[i]};` } $("div").text(content) }); });
在這裏博主曾經犯了個小錯誤,因爲onsuccess是回調函數,是異步操做,我卻想實現做用域的提高,真是愚蠢至極,公司老大說建議我用promise語法,可是一直沒成功,但願有會的童鞋能夠幫小小白解決一下,咱們如今點擊按鈕:效果以下:
此時的一個簡單的離線預覽已經作完啦,如今就算是吧ajax請求數據的方法刪除也好不影響咱們的預覽。由於是離線的呀!
彙總代碼:
HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>indexedDB</title> <script src="http://static.mschool.cn/jquery/latest/jquery.min.js"></script> </head> <body> <p>從本地數據庫裏面讀取的內容</p> <div> </div> <button>讀取內容觸發器</button> </body> <script> $(function () { let myDB = { name: "test", version: 1, db: null }; let arr = []; /***本地存儲數據庫的方法***/ function indexedDB(user) { /**建立數據庫**/ function openDB(name) { let version = 1; let request = window.indexedDB.open(name, version); request.onerror = function (e) { console.log(e.currentTarget.error.message); }; request.onsuccess = function (e) { myDB.db = e.target.result; }; request.onupgradeneeded = function (e) { let db = e.target.result; if (!db.objectStoreNames.contains("students")) { db.createObjectStore("students", {keyPath: "id"}); } console.log('DB version changed to ' + version); }; } let students = user; /*向數據庫裏面添加數據*/ function addData(db, storeName) { let transaction = db.transaction(storeName, 'readwrite'); let store = transaction.objectStore(storeName); for (let i = 0; i < students.length; i++) { store.add(students[i]); } } openDB(myDB.name); setTimeout(function () { addData(myDB.db, "students"); }, 1000); } /**本地數據庫的查詢**/ function getDataByKey(db, storeName, value, cb) { let transaction = db.transaction(storeName, 'readwrite'); let store = transaction.objectStore(storeName); let request = store.get(value); request.onsuccess = cb; } /****ajax獲取mysql數據庫****/ function result() { function Submit(url) { const Promises = new Promise(function (resolve, reject) { const handler = function () { if (this.readyState !== 4) { return; } if (this.status === 200) { resolve(this.response); } else { reject(new Error(this.statusText)); } }; const xrh = new XMLHttpRequest(); let formData = new FormData(); formData.append("id", "id"); xrh.onload = handler; xrh.open("post", url); xrh.responseType = "json"; xrh.send(formData); }); return Promises; } Submit("./select.php").then( function (data) { for (let i in data) { arr.push(eval("(" + data[i] + ")")) } }, function (error) { console.log("錯誤爲:", error) } ) }; result(); indexedDB(arr); $("button").click(() => { getDataByKey(myDB.db, "students", "1", function (e) { let text = e.target.result; let content = ""; for (let i in text) { content += `${i}爲${text[i]};` } $("div").text(content) }); }); }) </script> </html>
php:
<?php /** * Created by PhpStorm. * User: DELL * Date: 2017/12/6 * Time: 16:16 */ function postData($key,$default = ""){ return trim(isset($_REQUEST[$key])?$_REQUEST[$key]:$default); } $id = postData("id"); $conn = mysqli_connect("localhost", "root", "", "test") or die("鏈接失敗"); $conn->query("set names utf8"); $sql = "select * from user where ".$id." is not null"; $result = $conn->query($sql); $arr = array(); while ($row = $result->fetch_assoc()) { array_push($arr,json_encode($row)); } print_r(json_encode($arr)); $conn->close();