话不多说,上图上源码
1.实现效果如下图:
2.前端代码index.html
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>Ewangda 阿桂天山Ztree实战</TITLE>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="/static/css/bootstrapStyle/bootstrapStyle.css" type="text/css">
<script type="text/javascript" src="/static/js/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="/static/ztree/js/jquery.ztree.core-3.5.js"></script>
<script type="text/javascript" src="/static/ztree/js/jquery.ztree.excheck-3.5.js"></script>
<script type="text/javascript" src="/static/ztree/js/jquery.ztree.exedit-3.5.js"></script>
</HEAD>
<BODY>
<h2>Flask对Ztree节点的增加,修改与删除</h2>
<ul id="treeDemo" class="ztree"></ul>
</BODY>
</HTML>
<script >
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
var setting = {
view: {
addHoverDom: addHoverDom,
removeHoverDom: removeHoverDom,
selectedMulti: false
},
check: {
enable: true
},
data: {
simpleData: {
enable: true
}
},
edit: {
enable: true
},
callback : {
beforeRemove : beforeRemove,
beforeRename : beforeRename,
}
};
$(document).ready(function() {
$.getJSON($SCRIPT_ROOT+'/_get_tree','',function(data){
var zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, data);
zTreeObj.expandAll(true); //所有节点都会默认展开
})
});
var newCount = 1;
//-----------gtj 增加新节点
function addHoverDom(treeId, treeNode) {
var sObj = $("#" + treeNode.tId + "_span");
if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
var addStr = "<span class='button add' id='addBtn_" + treeNode.tId +
"' title='add node' onfocus='this.blur();'></span>";
sObj.after(addStr);
var btn = $("#addBtn_" + treeNode.tId);
if (btn) btn.bind("click", function() {
var ppname = prompt("请输入新节点名称");
if (ppname == null){
return;
}else if(ppname == ""){
alert("节点名称不能为空");
}else{
var zTree = $.fn.zTree.getZTreeObj("treeDemo");
$.post($SCRIPT_ROOT+'/_add_tree',
{pId:treeNode.id, name:ppname},
function(data){
if ($.trim(data) != null){
var treenode = $.trim(data);
zTree.addNodes(treeNode, {
pId : treeNode.id,
name : ppname
});
return false;
}
}
)
}
});
};
//-----------gtj 删除节点
function removeHoverDom(treeId, treeNode) {
$("#addBtn_" + treeNode.tId).unbind().remove();
};
function beforeRemove(treeId, treeNode) {
if (confirm("确认删除节点--" + treeNode.name + "--吗?")) {
$.ajax({
type: 'delete',
url: $SCRIPT_ROOT+'/_delete_tree',
data:{id:treeNode.id},
success: true
});
} else {
return false;
}
}
//-----------gtj 修改节点
function beforeRename(treeId, treeNode, newName) {
if (newName.length == 0) {
alert("节点名称不能为空.");
return false;
}
$.ajax({
type: 'post',
url: $SCRIPT_ROOT+'/_update_tree',
data:{id:treeNode.id, newname:newName},
success: true
})
return true;
}
</script>
#=============================================================
#---------------------阿桂天山 Ewangda--------------------------
"""
阿桂天山Ztree实战,对树节点的增加,修改与删除
"""
import op_sql
import json
from flask import Flask, render_template, request
app = Flask(__name__)
# Ztree管理
@app.route('/background')
def tree():
return render_template("index.html")
# 返回所有数据
@app.route('/_get_tree')
def get_tree():
return json.dumps(op_sql.transport())
# 增加节点的函数
@app.route('/_add_tree', methods=['GET', 'POST', 'DELETE'])
def add_node():
if request.method == 'POST':
parent_id = request.form['pId']
ename = request.form['name']
op_sql.insert('test-pub', 't_ztree', ename, parent_id)
return json.dumps({'pId': parent_id, 'name': ename})
# 删除结点的函数
@app.route('/_delete_tree', methods=['DELETE'])
def delete_node():
if request.method == 'DELETE':
eid = request.form['id']
op_sql.delete('test-pub', 't_ztree', eid)
return ''
# 更新节点名字的函数
@app.route('/_update_tree', methods=['POST'])
def update_node():
if request.method == 'POST':
eid = request.form['id']
newname = request.form['newname']
op_sql.update("test-pub", "t_ztree", eid, newname)
return ''
# 启动主页面
if __name__ == "__main__":
app.run(debug=True)
3.对数据库的操作op_sql.py
def insert(database, table, ename, pId):
conn = pymysql.connect(user="aaa", password="123xxxx", host="127.0.0.1", database=database)
cursor = conn.cursor()
# 写入语句
sql_insert = 'insert into %s(name,pId)values("%s","%s");' % (table, ename, pId)
try:
cursor.execute(sql_insert)
conn.commit()
# except Exception as e:
# db.rollback()
finally:
conn.close()
def update(database, table, eid, newname):
conn = pymysql.connect(user="aaa", password="123xxxx", host="127.0.0.1", database=database)
cursor = conn.cursor()
# 更新语句
sql_update = 'update %s set name = "%s" where id = "%s";' % (table, newname, eid)
try:
cursor.execute(sql_update)
conn.commit()
finally:
conn.close()
def delete(database, table, id):
conn = pymysql.connect(user="aaa", password="123xxxx", host="127.0.0.1", database=database)
cursor = conn.cursor()
# 删除语句
sql_delete = 'delete from %s where id =%s;' % (table, id)
try:
cursor.execute(sql_delete)
conn.commit()
finally:
conn.close()