passing json data from servlet to jsp to js file

前端 未结 2 1769
臣服心动
臣服心动 2021-02-10 09:16

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

相关标签:
2条回答
  • 2021-02-10 09:29

    You don't have to drop the JSON as a string - it's valid JavaScript syntax:

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

    When that's rendered by JSP, the end result — the HTML sent to the browser — will be something like:

    <body onload='init({"something": "some value", "whatever": "your data looks like"})'>
    

    Now the only thing you may want to do is HTML encode the JSON, since you're dropping it as an HTML attribute value:

    <body onload='init(${fn:escapeXml(jsonString)})'>
    

    Then your "init" function can expect a ready-to-use JavaScript object, with no need to call a JSON parser at all.

    0 讨论(0)
  • 2021-02-10 09:33

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

    0 讨论(0)
提交回复
热议问题