Chris
Chris

Reputation: 23

Problem working JSON objects from JSP to JS

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

Upvotes: 2

Views: 1660

Answers (1)

BalusC
BalusC

Reputation: 1108692

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>

Upvotes: 3

Related Questions