使用JSP中的JSON填充JSTree

时间:2015-01-15 15:20:29

标签: javascript ajax json jsp jstree

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

这是我的尝试:

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();

1 个答案:

答案 0 :(得分:1)

req.responseText.trim()返回一个字符串,因此您需要将此JSON转换为Javascript对象。

尝试以下方法:

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