本地存储数据库indexedDB实现离线预览的功能
今天在学习《高级JS编程》,看到离线存储,cookie和session都十分的熟悉,但是书中还提到了indexedDB和webSQL(已废弃),indexedDB可以像mysql一样建表,这就很有趣了,可以把后台获取来的数据统一放到indexedDB里面,那么即使断开连接,也能实现离线预览的功能啊,对于indexedDB的内容,这位博主的博客写的十分的详细,强烈推荐:https://www.cnblogs.com/dolphinX/p/3415761.html
好了,言归正传,开始我们的离线预览之旅吧:
1.准备一张sql的表,我建立了一个名为user的表,如下:
我们现在要做的功能是查找表里带id字段的内容然后存到indexedDB里面,再从indexDB里面进行取值
2.ajax进行取值运算:
html代码:
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转换类型,因为后台返回的都是字符串类型
3.php进行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();