阿桂天山的技术小结:Flask实现对Ztree树状节点的增改删操作

话不多说,上图上源码

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>

3.后端代码tree.py

#=============================================================
#---------------------阿桂天山 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()

最后,有关数据表结构及测试数据,Ztree的树节点显示,搜索查询等请参考我的另一篇博文

阿桂天山的技术小结:Flask对Ztree树节点搜索定位https://blog.csdn.net/gui818/article/details/133696956

相关推荐
小鹿( ﹡ˆoˆ﹡ )2 分钟前
深入探索 Seaborn:高级绘图的艺术与实践
python·信息可视化
hummhumm2 分钟前
Oracle 第29章:Oracle数据库未来展望
java·开发语言·数据库·python·sql·oracle·database
聪明的墨菲特i10 分钟前
Django前后端分离基本流程
后端·python·django·web3
工业3D_大熊16 分钟前
【虚拟仿真】CEETRON SDK在船舶流体与结构仿真中的应用解读
java·python·科技·信息可视化·c#·制造·虚拟现实
SEEONTIME25 分钟前
python-24-一篇文章彻底掌握Python HTTP库Requests
开发语言·python·http·http库requests
Bearnaise25 分钟前
PointMamba: A Simple State Space Model for Point Cloud Analysis——点云论文阅读(10)
论文阅读·笔记·python·深度学习·机器学习·计算机视觉·3d
哇咔咔哇咔1 小时前
【科普】conda、virtualenv, venv分别是什么?它们之间有什么区别?
python·conda·virtualenv
CSXB991 小时前
三十四、Python基础语法(文件操作-上)
开发语言·python·功能测试·测试工具
亚图跨际2 小时前
MATLAB和Python及R潜变量模型和降维
python·matlab·r语言·生物学·潜变量模型
IT古董2 小时前
【机器学习】决定系数(R²:Coefficient of Determination)
人工智能·python·机器学习