Search code examples
jsonjspmodel-view-controllerjstreejtree

Unable to dynamically load Json Arrays from JSP to a Jstree


I was trying to make a simple LDAP client to just retrieve the data from an LDAP server. I am returning array of JSON objects from the JSP. On click of any value I will get some data from online server. I am able to load the first set of array into a tree. The arrays got in the next step dont get attached to the JSTree. My codes:

function getGroupsStructure(id) {
console.log("in getGroupsStructure-->");
var paramId = "";

if(id == '') {
    console.log("in if-->");
    paramId = "c=de";
} else {
    console.log("in else-->");
    paramId = id;

}

  var params = {
  "DN" : paramId,

 };
  console.log("params-->",params);
   var getGroupsStructureForUserService = service(webURL + "sendingValues/getGroupsStructureForUser",params,"POST");
    getGroupsStructureForUserService.success(function(data) {
        console.log("in success-->dta-->",data);
        if(data.errorCode == '0') {
            console.log("in error code 0-->dta-->",data.treeData);
            $('.treeNode').jstree({
                'core': {
                    'data': function (obj, cb) {
                        cb.call(this,
                                data.treeData);
                }
                }
            });
            console.log("Tree Created...");
        } else {
            console.log("error code not 0--data-->",data);
        }

        $(document).off('click').on('click', '.treeNode a', function() {
            console.log("on click of a-->");
           var id = $(this).parent().attr('id');

           console.log("id-->",id);

           getGroupsStructure(id);
           console.log("after getGroupsStructure");
        });
    });
    getGroupsStructureForUserService.error(function(data) {
        console.log(" empty error");
    //    console.log(err);
    });
}

The JSP Code is

def NextLevelLDAP(String DN) {
        //  println "Next Level===>"
            assert ldap!=null
            def responseArray=[]
            def results=ldap.search('objectClass=*',DN,SearchScope.ONE)         //Will be triggered when + is pressed in GUI to get next level of tree
        //  assert results==null
            if(DN.startsWith("c="))
                {
                    JSONObject responseJson1=new JSONObject()
                    responseJson1.put("id", initialDN )
                    responseJson1.put("parent", "#")
                    responseJson1.put("text","Parent")
                    responseArray.add(responseJson1)
                    for(entry in results) {
                    //  println entry
                    //  println "In NextLevel Using InitialDN"
                        JSONObject responseJson=new JSONObject()
                        responseJson.put("id", entry.dn)
                        responseJson.put("parent", DN)
                        String tempResDN=entry.dn.toString()
                        def tempLength=tempResDN.length() - DN.length()
        //              println tempResDN
                        String tempName=tempResDN.substring(2,tempLength-1)
    //                  println tempName
                        responseJson.put("text",tempName)
                        responseArray.add(responseJson)
        //              println entry
                        println responseJson.toString()
                    }
                    return responseArray
                }
            if(results.size!=0)
            {
                for(entry in results) {
                    println entry

                    JSONObject responseJson=new JSONObject()
                    responseJson.put("id", entry.dn)
                    responseJson.put("parent", DN)
                    String tempResDN=entry.dn.toString()
                    def tempLength=tempResDN.length() - DN.length()
    //              println tempResDN
                    String tempName=tempResDN.substring(2,tempLength-1)
                    println tempName
                    responseJson.put("text",tempName)
                    responseArray.add(responseJson)
    //              println entry

                }
                return responseArray
            } 
          }

Please Ignore the way of getting the Parent ID. Its Something COmplicated. Please help me out how do I get The tree nodes created dynamically. I am just getting the fist level of the tree. The data on click for other levels is being shown in the console but not getting attached to the tree.

Thank you.


Solution

  • You have it the other way around - you need to create the tree and have it make the request for you, so instead of this:

    'data': function (obj, cb) {
        cb.call(this, data.treeData);
    }
    

    Use something like this:

    'data': function (obj, cb) {
        // you probably need to pass the obj.id as a parameter to the service
        // keep in mind if obj.id is "#" you need to return the root nodes
        service(...).success(function (data) {
            cb.call(this, data.treeData);
        });
    }
    

    This way you do not need to detach and reattach click handlers every time and it will work out of the box for opening nodes. If you want to open a node on click, you can use this:

    $('#tree').on('select_node.jstree', function (e, data) {
       data.instance.open_node(data.node);
    });
    

    So your whole code should look something like this:

    function load(id) {
        var params = {
            "DN" : id && id !== '#' ? id : "c=de"
        };
        return service(webURL + "sendingValues/getGroupsStructureForUser", params, "POST");
    }
    
    $('#tree')
        .jstree({
            'core' : {
                'data': function (obj, cb) {
                    load(obj.id).success(function (data) {
                        cb.(data.treeData);
                    });
                }
            }
        })
        .on('select_node.jstree', function (e, data) {
            data.instance.open_node(data.node);
        });
    

    Just make sure you mark the nodes your return as having children (set their children property to boolean true).