Pog*_*ips 4 javascript json jsp servlets
我得到了这个创建JSON数据的servlet,我希望将这些数据传递给jsp页面,该页面应该通过InfoVis工具包显示数据.
servlet.java
JSONObject json = new JSONObject();
JSONArray toplevel = new JSONArray();
JSONObject sublevel;
try{
json.put("id", "node" + 0);
json.put("name", "name" + 0);
int count = 5;
for(int i=1; i < count; i++){
sublevel = new JSONObject();
sublevel.put("id", "node" + i);
sublevel.put("name", "name" + i);
toplevel.put(sublevel);
}
json.put("children", toplevel);
} catch (JSONException jse) {
}
request.setAttribute("jsonString", json.toString());
RequestDispatcher dispatcher = request.getRequestDispatcher("graph.jsp");
dispatcher.forward(request, response);
Run Code Online (Sandbox Code Playgroud)
以下代码由InfoVis Toolkit提供,我不确定是否可以更改.或者至少我没有足够的经验来改变它.
graph.jsp
<body onload="init('${jsonString}');">
Run Code Online (Sandbox Code Playgroud)
spacetree.js
function init(jsonString){
var json = jsonString;
Run Code Online (Sandbox Code Playgroud)
最初只是函数调用
<body onload="init()">
Run Code Online (Sandbox Code Playgroud)
但init()函数具有硬编码的JSON变量,这当然没有用.所以我正在寻找一种方法来实现这种动态.但是由于字符串中的引用它现在完全混淆了onload = init()函数调用..
便宜又简单的方法是修改JSP,以便输出:
<script>
var theData = ${jsonString};
</script>
<body onload="init(theData);">
Run Code Online (Sandbox Code Playgroud)
这样做的缺点是它会创建一个全局变量,但是如果你init以这种方式调用init,那么它已经是一个全局变量,所以这艘船已经航行了.:-)