在做后台管理界面的时候,几乎少不了的一个结构就是树形结构,用来做菜单导航;
那么,最希望的就是树结构的所有数据都是读取的数据库,而不是直接代码当中写死,那我们就一步一步来看:
一,建表
字段通常包括:id,text,url,pid
id
text
url
pid
1
a
0
2
b
test.html
1
二,使用nodeJS连接数据库
const mysql = require('mysql'); //注入MySQL模块
const connection = mysql.createConnection({ //连接数据库的信息
host:'', //数据库的地址,如:localhost
user:'', //登录名 默认root
password:'', //登录密码
database:'' //数据库名字
});
connection.connect(); //创建连接
三,读取数据
connection.query('SELECT*FROM 表名',function(err,rows){}); //rows为读过来的数据
四,把读过来的数据转成树结构的json数据
//举例读取的数据为list的数据
var list = [{"