首先,我建议使用 JavaScript 对象语法而不是 UL/LI 样式,因为它的性能更高(缺点:即使禁用 JavaScript,也会呈现 UL 标记)。
诀窍是,简单地将自定义属性添加到节点数据(在此示例中,我们可以将其称为“url”),如下所示:
{title: "Google", url: "http://www.google.com"}
然后,在激活处理程序中,像这样访问这个属性:dtnode.data.url。
摘自示例页面 (http://wwwendt.de/tech/dynatree/doc/sample-iframe.html):
$("#tree").dynatree({
onActivate: function(dtnode) {
// Use our custom attribute to load the new target content:
if( dtnode.data.url )
$("[name=contentFrame]").attr("src", dtnode.data.url);
},
children: [
{title: "Search engines", isFolder: true, expand: true,
children: [
{title: "Google", url: "http://www.google.com"},
{title: "Yahoo", url: "http://yahoo.com"}
]
},
{title: "jQuery", isFolder: true, expand: true,
children: [
{title: "jQuery", url: "http://www.jquery.com"},
{title: "jQuery UI", url: "http://ui.jquery.com"},
{title: "API browser", url: "http://api.jquery.com"},
{title: "dynatree", url: "http://code.google.com/p/dynatree/"}
]
}
]
});
如果您想使用 Ajax 请求,以 JSON 格式从服务器接收此数据,
这个示例 - 用 Python 编写 - 可能会给出一个方向:
# Build node list as JSON formatted string:
res = "["
res += "{ 'title': 'Node 1', 'key': 'k1', 'isLazy': true, 'url': 'http://foo.com' },"
res += "{ 'title': 'Node 2', 'key': 'k2', 'isLazy': true, 'url': 'http://bar.com' }"
res += "]"
# Add support for the JSONP protocol:
# This means, if the request URL contains an argument '?callback=xxx',
# wrap the result as 'xxx(result)'
if "callback" in argDict:
res = argDict["callback"] + "(" + res + ")"
# Make sure, content type is JSON:
start_response("200 OK", [("Content-Type", "application/json")])
# Return result (the square brackets are Python / WSGI specific):
return [ res ]
请注意,在 Ajax/JSON 模式下,您不必返回分层结构。相反,您可以将节点标记为lazy,以便在第一次展开节点时发送另一个请求。