阿桂天山的技术小结: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

相关推荐
浊酒南街1 小时前
决策树python实现代码1
python·算法·决策树
FreedomLeo12 小时前
Python机器学习笔记(十三、k均值聚类)
python·机器学习·kmeans·聚类
星光樱梦2 小时前
32. 线程、进程与协程
python
阿正的梦工坊2 小时前
深入理解 PyTorch 的 view() 函数:以多头注意力机制(Multi-Head Attention)为例 (中英双语)
人工智能·pytorch·python
西猫雷婶3 小时前
python学opencv|读取图像(十九)使用cv2.rectangle()绘制矩形
开发语言·python·opencv
海绵波波1073 小时前
flask后端开发(10):问答平台项目结构搭建
后端·python·flask
赵谨言4 小时前
基于python网络爬虫的搜索引擎设计
爬虫·python·搜索引擎
code04号4 小时前
python脚本:批量提取excel数据
开发语言·python·excel
hakesashou4 小时前
python如何打乱list
开发语言·python
silver6875 小时前
使用 Python 操作 Excel 表格
python