使用 JSP 中的 JSON 填充 JSTree

Populate JSTree with JSON from JSP

我正在尝试使用从 JSP 文件中检索到的 JSON 字符串填充 JSTree。

这是我的尝试:

function initDirs() {
    var req = new XMLHttpRequest();
    req.overrideMimeType("application/json");
    req.open("GET", "svntojson.jsp?expandedNodePath=/root", true); 
    req.onreadystatechange = function receive() {
        if (req.readyState == 4) {
            createTree(req.responseText.trim());
        }
    };
    req.send();
}    

initDirs();

function createTree(jsonData) {
    console.log(jsonData);
    $('#treeview').jstree({
        'core' : {
            'data' : jsonData
        }
    });
}

很遗憾,jstree 是空的。我记录了返回的 json,这对我来说很不错:

 { "id" : "root", "parent" : "#", "text" : "root" },
 {"id":"branches","parent":"root","text":"branches"},
 {"id":"README.txt","parent":"root","text":"README.txt"},
 {"id":"svn.ico","parent":"root","text":"svn.ico"},
 {"id":"Desktop.ini","parent":"root","text":"Desktop.ini"},
 {"id":"vgt","parent":"root","text":"vgt"},
 {"id":"trunk","parent":"root","text":"trunk"},
 {"id":"format","parent":"root","text":"format"} 

如果手动设置返回的 json 它有效:

function createTree(jsonData) {
    console.log(jsonData);
    $('#treeview').jstree({
        'core' : {

            'data' : [
                 { "id" : "root", "parent" : "#", "text" : "root" },
                 {"id":"branches","parent":"root","text":"branches"},
                 {"id":"README.txt","parent":"root","text":"README.txt"},
                 {"id":"svn.ico","parent":"root","text":"svn.ico"},
                 {"id":"Desktop.ini","parent":"root","text":"Desktop.ini"},
                 {"id":"vgt","parent":"root","text":"vgt"},
                 {"id":"trunk","parent":"root","text":"trunk"},
                 {"id":"format","parent":"root","text":"format"} 
            ]
        }
    });
}

谁能帮我在树视图中显示我返回的 json?

编辑: 这是我的最终解决方案:

    function initDirs() {
    var req = new XMLHttpRequest();
    var path = "root/";
    req.overrideMimeType("application/json");
    req.open("GET", "svntojson.jsp?expandedNodePath="+path, true); 
    req.onreadystatechange = function receive() {
        if (req.readyState == 4) {
           var jsonData = JSON.parse(req.responseText.trim());
           $('#treeview').jstree(true).settings.core.data = jsonData;
           $('#treeview').jstree(true).refresh();
        }

    };

    req.send();
}    


initDirs();

req.responseText.trim() return一个字符串,所以你需要把这个JSON转换成一个Javascript对象。

尝试以下操作:

if (req.readyState == 4) {
    var respData = JSON.parse(req.responseText.trim());
    createTree(respData);
}