Technical summary of Agui Tianshan: Flask searches and locates Ztree tree nodes

Without further ado, here’s the source code in the picture above

1. First look at the renderings

2. Front-end page part:

1)Page

<!DOCTYPE html>
<HTML>

<HEAD>
    <TITLE>Ewangda Agui Tianshan’s Ztree practice</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 implements the filtering function of ztree nodes -->
    <script type="text/javascript" src="/static/ztree/js/jquery.ztree.exhide-3.5.js"></script>

</HEAD>

<BODY>
    <h2>Ztree with search and positioning function</h2>
    <div class="input-group" style="width:300px">
        <input type="text" id="search-input" onkeyup="autoMatchForZtree();" class="form-control" placeholder="Fuzzy query" 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) Front-end javascript script

<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 All nodes will be expanded by default
    })

});

/*** Function: gtj searches for matching tree nodes ***/
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 & amp; & amp; 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 & amp; & amp; 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. Backend Flask code

1)searchztree.py

#============================================== ===============
#---------------------Agui Tianshan Ewangda------------------------ --
import op_sql
import json

from flask import Flask, render_template, request

app = Flask(__name__)


# Front-end main page
@app.route('/')
def searchztree():
    return render_template('searchztree.html')


#Return all data in the background
@app.route('/_get_tree')
def get_tree():
    return json.dumps(op_sql.transport())


# Start the main page
if __name__ == "__main__":
    app.run(debug=True)

2) Connect to the database to obtain data:

2.1) mysql table creation statement and test data

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', 'Digital Intelligence Service', '1');
INSERT INTO t_ztree VALUES ('3', 'Innovative Visual Service', '1');
INSERT INTO t_ztree VALUES ('4', 'Precision Series', '2');
INSERT INTO t_ztree VALUES ('5', 'fine series', '2');
INSERT INTO t_ztree VALUES ('8', 'EDS Enterprise Digital Service Platform', '4');
INSERT INTO t_ztree VALUES ('9', 'PDS Precision Digital Service Cloud Platform', '4');
INSERT INTO t_ztree VALUES ('23', 'Seiko series', '2');
INSERT INTO t_ztree VALUES ('36', 'Exquisite series', '3');
INSERT INTO t_ztree VALUES ('37', 'AR smart e-commerce', '36');
INSERT INTO t_ztree VALUES ('38', 'Wonderful Series', '3');
INSERT INTO t_ztree VALUES ('39', 'Large screen display', '38');
INSERT INTO t_ztree VALUES ('40', 'Smart lips', '37');
INSERT INTO t_ztree VALUES ('41', 'Smart Mirror', '37');

2.2) Generate ztree data function file 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()

# Standardize the database query data to json data for transmission to the background
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

Summary: All the content is here, please give it a thumbs up if it is useful to you!!!

Final note: In order for tree nodes to be filtered, you must have the ztree.exhide library

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeWeb application development Flask376803 people are learning the system