passing json data from servlet to jsp to js file
javascript, json, jsp, servlets
Solution
The cheap and easy way is to modify the JSP so it outputs this:
<script>
var theData = ${jsonString};
</script>
<body onload="init(theData);">
The downside to that is that it creates a global variable, but if you're calling `init` in that way, `init` is already a global, so that ship has sailed. :-)
Problem
I got this servlet which creates JSON data and I want to pass this data on to a jsp page which is supposed to display the data via the InfoVis toolkit. 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); ``` The following Code is provided by the InfoVis Toolkit and I'm not sure if it can be changed. Or at least I don't have enough experience in JS to change it. graph.jsp ``` <body onload="init('${jsonString}');"> ``` spacetree.js ``` function init(jsonString){ var json = jsonString; ``` Originally the function call is only ``` <body onload="init()"> ``` but the init() function has the JSON variable hardcoded, which is of course not useful at all. So I'm looking for a way to make that dynamic. But since theres quotations inside the string it now totally messes up the onload=init() function call..