A brief analysis of the tree guide in jQuery EasyUI

  • 2020-05-07 19:10:14
  • OfStack

This paper records that when I led the members to develop a small module function, I needed to use the pop-up window to load the tree cascade unit selection, and finally decided to use jQuery+EasyUI plug-in for development. However, when using the tree plug-in in EasyUI, I ran into a lot of trouble. In order to provide the display speed of the pop-up tree, the number of nodes is loaded asynchronously, the root node is loaded first, and then the child nodes are loaded according to the node clicked.

Often, the result is not the same as expected. After several days of confusion, the child node is loaded dynamically after expansion, but the data filled before cannot be emptied after contraction. In the second expansion, the child node was reloaded once more, causing the data to be displayed repeatedly, and no method to clear the child node was provided. Tried all kinds of ways to solve this problem, can only change another form to load the value of the child node, save the value of each node, judge whether there is already exists, there is not to load.

See examples of the two methods:


var treeTitle = ' Selection list ';
var treeUrl = '../DataAshx/getTreeNode.ashx?pid=-1';
var nodeExp=false;
var nodekeep="";
var rows;
var noinf=0;
$(function() {
    $('#treewindow').window({
        title: treeTitle,
        width: 400,
        height: 400,
        modal: true,
        shadow: false,
        closed: true,
        resizable: false,
        maximizable: false,
        minimizable: false,
        collapsible: false
    });
});
function treeWindowOpen(name,rowIndx) {
    $('#treewindow').window('open');
    nodekeep="";
    nodeExp=false;
    rows=rowIndx.toString();
    $('#basetree').tree({
        checkbox: true,
        animate: true,
        url: treeUrl+"&coln="+escape(name.toString()),
        cascadeCheck: true,
        onlyLeafCheck: false,
        onBeforeExpand: function(node, param) {
//------------ The first 1 Method: load child node values asynchronously -------------
//            $('#basetree').tree('options').url = "../DataAshx/getTreeNode.ashx?pid=" + node.id+"&coln="+escape(name.toString());
//------------ The first 2 Methods: Ajax Method returns child nodes Json Value, the use of append Method loads child nodes       
        $.ajax({
                type: "POST",
                url: "../DataAshx/getTreeNode.ashx?pid=" + node.id+"&coln="+escape(name.toString())+"&casn="+escape(node.attributes.cas.toString()),
                cache: false,
                async: false,
                dataType: "json",
                success: function(data) {
                    if(nodekeep.indexOf(node.id)==-1)
                    {
                     append(data, node);
                     nodeExp = true;
                    }
                }
            });
            $("#radCollapse").removeAttr("checked");
        },
        onLoadError:function(Error)
        {
            $.messager.alert(' prompt ', ' Query error ', 'error');
            if(nodeExp==false)
            {
                $("#basetree").children().remove();
            }
        },
        onLoadSuccess:function(success)
        {
            var child=$("#basetree").children().length;
            noinf++;
            if(child==0&&noinf>1)
            {
                $.messager.alert(' prompt ', ' The data doesn't exist ', 'Info');
            }
        }
    });
}
function treeWindowClose() {
    $('#treewindow').window('close');
    nodekeep="";
    nodekeep=false;
}
function treeWindowSubmit() {
    var nodes = $('#basetree').tree('getChecked');
    var info = '';
    if (nodes.length > 0) {
        for (var i = 0; i < nodes.length; i++) {
            if (info != '') { info += ','; }
            info += nodes[i].text;
        }
        //alert(JSON.stringify(nodes));
    }
    else {
        var node = $('#basetree').tree('getSelected');
        if (node != null) {
            info = node.text;               
        }
    }
    $("#"+rows).val(info);
    $('#treewindow').window('close');
    nodekeep="";
    nodeExp=false;
}
// Expand all
function collapseAll() {
    $("#radCollapse").attr("checked", "checked");
    var node = $('#basetree').tree('getSelected');
    if (node) {
        $('#basetree').tree('collapseAll', node.target);
    } else {
        $('#basetree').tree('collapseAll');
    }
}
// All contract
function expandAll() {
    var node = $('#basetree').tree('getSelected');
    if (node) {
        $('#basetree').tree('expandAll', node.target);
    } else {
        $('#basetree').tree('expandAll');
    }
}
// Add child node
function append(datas,cnode) {
    var node = cnode;
    $('#basetree').tree('append', {
        parent: node.target,
        data: datas
    });
    nodekeep+=","+node.id;
}
// Reload the
function reload() {
    var node = $('#basetree').tree('getSelected');
    if (node) {
        $('#basetree').tree('reload', node.target);
    } else {
        $('#basetree').tree('reload');
    }
}
// Delete child node
function remove() {
    var node = $('#basetree').tree('getSelected');
    $('#basetree').tree('remove',node.target);
}

Page getTreeNode.ashx returns tree node JSON data:


<%@ WebHandler Language="C#" Class="getTreeNode" %>
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic; public class getTreeNode : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        DataTable dt = (DataTable)context.Session["viewmaintain"];
        string parentId = string.Empty;
        string resultStr = string.Empty;
        string attributes = string.Empty;
        string colName = string.Empty;
        string sql = string.Empty;
        string Casname = string.Empty;
        bool colt = false;
        string icon = "icon-profile";
        if (!string.IsNullOrEmpty(context.Request.QueryString["pid"]))
        {
            parentId = context.Request.QueryString["pid"].ToString();
        }
        if ((!string.IsNullOrEmpty(context.Request.QueryString["coln"])) && (string.IsNullOrEmpty(context.Request.QueryString["casn"])))
        {
            colName = HttpUtility.UrlDecode(context.Request.QueryString["coln"].ToString());
            if (dt != null)
            {
                bool pt = true;
                while (pt)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Casname = dt.Rows[i]["view_colname"].ToString();
                        if (dt.Rows[i]["view_colname"].ToString() == colName)
                        {
                            if (dt.Rows[i]["view_cas"].ToString() != null&&dt.Rows[i]["view_cas"].ToString() !="")
                            {
                                colName = dt.Rows[i]["view_cas"].ToString();
                            }
                            else
                            {
                                colt = true;
                                sql = dt.Rows[i]["view_sql"].ToString();
                                pt = false;
                            }
                            break;
                        }
                    }
                }
            }
        }
        if ((!string.IsNullOrEmpty(context.Request.QueryString["casn"])) && (!string.IsNullOrEmpty(context.Request.QueryString["coln"])))
        {
           string casnName = HttpUtility.UrlDecode(context.Request.QueryString["casn"].ToString());
           colName = HttpUtility.UrlDecode(context.Request.QueryString["coln"].ToString());
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Casname = dt.Rows[i]["view_colname"].ToString();
                    if (dt.Rows[i]["view_cas"].ToString() == casnName && casnName != colName)
                    {
                        colt = true;
                        sql = dt.Rows[i]["view_sql"].ToString();
                        break;
                    }
                }
            }
        }
        try
        {
            if (parentId != "" && colt == true)
            {
                // The code to get the list of data is omitted here
                List<TreeInfo> ltree = DAL_TreeInfo.GetItemValue(parentId, sql);
                resultStr = "";
                resultStr += "[";
                if (ltree.Count > 0)
                {
                    foreach (TreeInfo item in ltree)
                    {
                        attributes = "";
                        attributes += "{\"cas\":\"" + Casname;
                        attributes += "\",\"val\":\"" + item._text + "\"}";
                        resultStr += "{";
                        resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"iconCls\": \"{2}\", \"attributes\": {3}, \"state\": \"closed\"", item._id, item._text, icon, attributes);
                        resultStr += "},";
                    }
                    resultStr = resultStr.Substring(0, resultStr.Length - 1);
                }
                resultStr += "]";
            }
            else
            {
                resultStr = "[]";
            }
        }
        catch (Exception ex)
        {
            resultStr = " error ";
        }
        context.Response.Write(resultStr);
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

 
The key code is already on it, so it is the only way to solve it at present. If you have time, you can extend tree to 1 and add a method to clear the child nodes, which should be easier to implement.

My younger brother is here to show his shame. I don't know if any experts and colleagues have encountered similar problems or have other better solutions. Welcome to communicate here.


Related articles: