我目前正在使用d3和json对象实现数据。可以在此处找到此类图表的工作示例:http://bl.ocks.org/950642。如果您知道d3,您当然可以直接跳转到我的问题部分。
所以,基本上在我的模板中,我有最少的必要代码:
<div id="main" class="lift:surround?with=default;at=content">
<div class="lift:GraphVisual.showGraph"></div>
</div>
然后在我的代码段(GraphVisual.scala
)中,我有以下内容:
def showGraph = {
<h3>Bachelor 5/6 - Communication Systems</h3> ++
<div id="graph-container" width="500px" height="100px">
<script type="text/javascript" src="static/scripts/graph_script.js></script>
</div>
在定义图表(graph_script
)的javascript文件中,我主要有以下内容
var vis = d3.select("#graph-container").append("svg:svg")
d3.json("static/scripts/jsonData.json", function(json) {
//Do stuff
}
如果我将json数据存储在一个文件中,如上所示,一切正常。现在我想用升力生成我的json对象。所以我想有一个函数返回Lift中图形的json对象表示,并在脚本中使用它(应该是静态的)。
假设我有以下值来定义我的图表:
val graph = JObject(JField("nodes", JArray(List(...))), JField("links", JArray(List)))
我尝试将此图表定义为d3脚本上方脚本中的变量:
<script>{JsCrVar("myGraph", graph).toJsCmd}</script>
使用这种方法我有变量myGraph
这个定义很好,但我不知道如何在graph_script.js
答案 0 :(得分:2)
您可以将json数据检索移动到REST API。
object MyGraphApi extends RestHelper {
serve {
case Req("graph" :: Nil, _, GetRequest) => {
JsonResponse(myGraphObject)
}
}
}
然后你可以使用/ graph url将ajax拉入页面。
答案 1 :(得分:0)
Lukasz的解决方案,使用REST API完全正常。在我的研究期间,我还发现我的问题只是一个javascript问题:我不需要使用d3.json(...)
。
所以我只需删除函数d3.json(...)
并将所有内容放在其中。然后,只需拨打mygraph.nodes
,而不是json.nodes
。