将json数据从servlet传递到jsp到js文件 [英] passing json data from servlet to jsp to js file

查看:393
本文介绍了将json数据从servlet传递到jsp到js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这个创建JSON数据的servlet,我希望将这些数据传递给jsp页面,该页面应该通过InfoVis工具包显示数据。

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

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);

以下代码由InfoVis Toolkit提供,我不确定是否可以更改。或者至少我没有足够的经验来改变它。

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

graph.jsp

<body onload="init('${jsonString}');">

spacetree.js

spacetree.js

function init(jsonString){

    var json = jsonString;

最初函数调用只是

<body onload="init()">

但init()函数的JSON变量是硬编码的,当然这根本没用。所以我正在寻找一种方法来实现这种动态。但是由于字符串中的引用它现在完全混淆了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..

推荐答案

廉价和简单的方法是修改JSP,使其输出:

The cheap and easy way is to modify the JSP so it outputs this:

<script>
var theData = ${jsonString};
</script>
<body onload="init(theData);">

这样做的缺点是它会创建一个全局变量,但是如果你调用 init 就这样, init 已经是全球性的,所以这艘船已经航行了。 : - )

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. :-)

这篇关于将json数据从servlet传递到jsp到js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆