我正在尝试使用从 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"}
]
}
});
}
有人可以帮助我在 TreeView 中显示返回的 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);
}
关于javascript - 使用 JSP 中的 JSON 填充 JSTree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27966724/