Reputation: 7389
I am trying to populate a JSTree with a JSON String which i retrieve from a JSP file.
This is my attempt:
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
}
});
}
Unfortunately the jstree is empty. I logged the returned json which looks good to me:
{ "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"}
If is set the returned json manually it works:
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"}
]
}
});
}
Anyone who can help me to show my returned json in the treeview ?
EDIT: This is my final solution:
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();
Upvotes: 0
Views: 938
Reputation: 4997
req.responseText.trim()
return a string, so you need to convert this JSON into a Javascript object.
Try the following :
if (req.readyState == 4) {
var respData = JSON.parse(req.responseText.trim());
createTree(respData);
}
Upvotes: 1