easyui-tree

今天在用easyui 写一棵树,根据用户的所属部门来获取用户信息,结果出现了下面的问题:

根据如图所示api提供的方法:

我的代码是这样的

$('#userTree').tree({
            checkbox: true,
            url: 'roleAction/getUserTreeByRole.do',
            onClick:function(node){
            alert('you click '+node.text);
            }
        });
<font color="red">*</font><font size="2px">关联用户: </font>
<ul id="userTree" ></ul>

结果在任何一个浏览器中都无法得到想要的树,无奈下,尝试使用静态的方法来加载树,如下:

$('#userTree').tree({
            data:[{text: 'Item1',state: 'closed',children: [{text: 'Item11'},{text: 'Item12'}]},{text: 'Item2'}]
        });

结果得到了想要的树结构:

既然传data的方式可以显示出树结构,于是我决定采用ajax的方式来向后台请求数据,再将json数据作为data传输给tree,代码如下:

function initTree(){
   $.ajax({
             type : "post",
            //dataType: "json", 
            url: "roleAction/getUserTreeByRole.do",
            contentType : "application/x-www-form-urlencoded",
            success: function(data){
            //为什么一定要加eval呢?
            treedata = eval("(" + data + ")");
               $('#userTree').tree({
                    data: treedata
                });
                        
                     }
         });

}

后台给另一个假的数据来模拟,代码如下:

/**
     * 获取用户树
     * 
     * @return
     * @throws Exception 
     */
    @ResponseBody
    @RequestMapping("/getUserTreeByRole")
    public String getUserTreeByRole(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String  result= "[{text: 'Item1',state: 'closed',children: [{text: 'Item11'},{text: 'Item12'}]},{text: 'Item2'}]";
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(result);
        return null;
    }

在页面加载的时候,调用inittree()方法,结果也可以成功的显示上图显示的树结构,问题解决了,但是疑惑还存在:

1)为什么第一种api中提到的方法无法加载树结构?

2)在这个过程中,如果没有用eval()方法,也无法得到想要的结果,那么此处为什么一定要用到eval方法呢?

web开发过程中的问题总结
原文地址:https://www.cnblogs.com/muwanqing/p/4831575.html