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.

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to pass JSON object to JSP? I need the JSON objects to use in Javascript.
Is it bad to mix EL and JS together?
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: stackoverflow.com/questions/4112686/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.