2
<head>
    <script>
        function getInfo(o)
        {
            var obj=o;
            document.getElementById('test').innerHTML=obj.name1;
            document.getElementById('test2').innerHTML=obj.name2;
        }
    </script>
</head>

<body>
    <input type="button" value="submit" onclick='getInfo(${json})' />
    <p>JSON values should appear below.</p>
    <div id="test"></div>
    <div id="test2"></div>
</body>

I'm trying to load the JSON object when the page loads, but I've been unsuccessful with various different ways... c:set var, body onload, mixing JSTL and JS...

Is there a way to load JSON objects as the page loads?

It's based on this example: http://java-x.blogspot.com/2007/04/using-json-from-java.html

Currently, it works, it loads the JSON object when I click the button, but I don't want clicking anything.

Chris
  • 23
  • 3

1 Answers1

3

Just remove the button and call the function by window.onload.

window.onload = function() {
    var obj = ${json};
    document.getElementById('test').innerHTML = obj.name1;
    document.getElementById('test2').innerHTML = obj.name2;
}

I however wonder how it makes sense to delegate the render job to an onload JS with server-side provided data. You could also just use JSP taglibs/EL for this.

<div id="test">${bean.name1}</div>
<div id="test2">${bean.name2}</div>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Is there a way to pass JSON object to JSP? I need the JSON objects to use in Javascript. – Chris Aug 25 '11 at 22:09
  • Is it bad to mix EL and JS together? – Chris Aug 25 '11 at 22:21
  • Depends on the fuctional requirement. If the JS is technically unnecessary because the very same job could be done by alone JSP taglibs/EL, then it can indeed be considered bad. See also the 2nd code example in my answer. However, if you need to retrieve JSON upon some JS event (and thus NOT during onload!), then you usually follow the Servlet+Ajax practice as outlined in the answer here: http://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax – BalusC Aug 25 '11 at 22:23