话不多说,上图上源码

1.先看效果图

阿桂天山的技术小结:Flask对Ztree树节点搜索定位-LMLPHP

阿桂天山的技术小结:Flask对Ztree树节点搜索定位-LMLPHP

2.前端页面部分:

        1)页面

<!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">

<link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

    <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>
    <!--  gtj 实现对ztree节点筛选功能用  -->
    <script type="text/javascript" src="/static/ztree/js/jquery.ztree.exhide-3.5.js"></script>

</HEAD>

<BODY>
    <h2>具有搜索定位功能的Ztree</h2>
    <div class="input-group" style="width:300px">
        <input type="text" id="search-input" onkeyup="autoMatchForZtree();" class="form-control" placeholder="模糊查询" style="border: 1px solid #cccccc; border-right: 0;"/>
        <div class="input-group-addon"><i class="glyphicon glyphicon-search"></i></div>
    </div>
    <ul id="treeDemo" class="ztree"></ul>
</BODY>

</HTML>

        2)前端javascript脚本

<script >
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
var setting = {
    view: {
        selectedMulti: false
    },
    check: {
        enable: true
    },
    data: {
        simpleData: {
            enable: true
        }
    },
};

$(document).ready(function() {
    $.getJSON($SCRIPT_ROOT+'/_get_tree','',function(data){
            var zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, data);
            zTreeObj.expandAll(true); //---gtj 所有节点都会默认展开
    })

});

/*** 功能:gtj 搜索匹配树节点 ***/
function searchChildren(keyword, children){
    if(children == null || children.length == 0){
        return false;
    }
    for(var i = 0; i < children.length; i++){
        var node = children[i];
        if(node.name.indexOf(keyword) != -1 && node.isHidden === false){
            return true;
        }
        var result = searchChildren(keyword, node.children);
        if(result){
            return true;
        }
    }
    return false;
}

function searchParent(keyword, node){
    if(node == null){
        return false;
    }
    if(node.name.indexOf(keyword) != -1 && node.isHidden === false){
        return true;
    }
    return searchParent(keyword, node.getParentNode());
}

var hiddenNodesForZtree = [];

function autoMatchForZtree(){
    setTimeout(function(){
        var ztreeObj = $.fn.zTree.getZTreeObj("treeDemo");

        ztreeObj.showNodes(hiddenNodesForZtree);

        function filterFunc(node){
            var keyword = $("#search-input").val();

            if(searchParent(keyword, node) || searchChildren(keyword, node.children)){
                return false;
            }
            return true;
        };

        hiddenNodesForZtree = ztreeObj.getNodesByFilter(filterFunc);

        ztreeObj.hideNodes(hiddenNodesForZtree);

    }, 300);
}

</script>

3.后端Flask代码

        1)searchztree.py

#=============================================================
#---------------------阿桂天山 Ewangda--------------------------
import op_sql
import json

from flask import Flask, render_template, request

app = Flask(__name__)


# 前端主页面
@app.route('/')
def searchztree():
    return render_template('searchztree.html')


# 后台返回所有数据
@app.route('/_get_tree')
def get_tree():
    return json.dumps(op_sql.transport())


# 启动主页面
if __name__ == "__main__":
    app.run(debug=True)

        2)连接数据库获取数据:

                2.1)mysql建表语句及测试数据

CREATE TABLE `t_ztree` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `pId` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_ztree
-- ----------------------------
INSERT INTO t_ztree VALUES ('1', 'Ewangda', '0');
INSERT INTO t_ztree VALUES ('2', '数智化服务', '1');
INSERT INTO t_ztree VALUES ('3', '创新视觉服务', '1');
INSERT INTO t_ztree VALUES ('4', '精准系列', '2');
INSERT INTO t_ztree VALUES ('5', '精细系列', '2');
INSERT INTO t_ztree VALUES ('8', 'EDS企业数字服务平台', '4');
INSERT INTO t_ztree VALUES ('9', 'PDS精准数字服务云平台', '4');
INSERT INTO t_ztree VALUES ('23', '精工系列', '2');
INSERT INTO t_ztree VALUES ('36', '精致系列', '3');
INSERT INTO t_ztree VALUES ('37', 'AR智能电商', '36');
INSERT INTO t_ztree VALUES ('38', '精彩系列', '3');
INSERT INTO t_ztree VALUES ('39', '大屏展示', '38');
INSERT INTO t_ztree VALUES ('40', '智能美唇', '37');
INSERT INTO t_ztree VALUES ('41', '智能靓镜', '37');

        2.2)生成ztree数据函数文件op_sql.py

def query(sql_select):
    conn = pymysql.connect(user="aaa", password="123xxxx", host="127.0.0.1", database="test-ztree")
    cursor = conn.cursor()
    try:

        cursor.execute(sql_select)
        result = cursor.fetchall()
        return result
    finally:
        conn.close()

# 将数据库查询数据标准化json数据以便传入后台
def transport():
    zNdodes = []

    for i in query("select id, name, pId from t_ztree;"):
        zNdode = {}
        zNdode['id'] = i[0]
        zNdode['name'] = i[1]
        zNdode['pId'] = i[2]

        zNdodes.append(zNdode)
    return zNdodes

总结:所有内容都在这了,对你有用给个赞吧!!!

最后要注意:要让树节点能被筛选,一定要有ztree.exhide库

阿桂天山的技术小结:Flask对Ztree树节点搜索定位-LMLPHP             

10-10 14:14