用 JSP 中的 JSON 填充 JSTree

Populate JSTree with JSON from JSP

本文关键字:填充 JSTree JSON 中的 JSP      更新时间:2023-09-26

我正在尝试使用从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()返回一个字符串,所以你需要把这个JSON转换成一个Javascript对象。

尝试以下操作:

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