views:

32

answers:

2

How to read JSONObject in dojo?

I have a JSONObject in my jsp.

JSONObject  myJSONObj = new JSONObject();

How can I read this myJSONObj in my dojo or *.js file, in 'onload function'.

A: 

might want to try this:

window.load = function(){
 var myjson = <%= getJSON() %>
 //using myjson
}

getJSON is a function which returns myJSONObj as JSON formatted String

update: short example. hope it helps

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<%
class Foor{
    public String getJSON(){
        return "{foo:'bar'}";
    }
}

Foor myfoo = new Foor();

%>
<script language=javascript>
var myjson = <%= myfoo.getJSON()%>
alert(myjson.foo);
</script>
</head>
<body>

</body>
</html>
jebberwocky
@jebberwocky: I tried this, but it gives me "illegal XML character" error.
Rachel
@rachel hope the updated example helps
jebberwocky
Since the output of "myfoo.getJSON()" will be considered a string within the script tag you should wrap it like this:var myjson = dojo.fromJson('<%= myfoo.getJSON() %>');and I think that example will work...
subhaze
@subhaze, if I am creating instance of Foor class 'myfoo' in my JSP,then will myfoo is accessible in dojo (js file). I tried this also. But whenever I say var **myjson = dojo.fromJson('<%= myfoo.getJSON() %>');** then code doesnot get compiled even. Kindly give your suggestion.
Rachel
I've not worked with JSP before but with PHP that's how I've done it. If your code is similar to above where you mix server-side code with HTML then I would think you're instance of Foor class 'myfoo' should work as stated above with the modification of using the dojo.fromJson to make sure it's valid JSON as {foo:'bar'} is not. http://pastebin.com/bL9s9xYa That's about all I can think of sorry :/
subhaze
Maybe just try separating it all out. A page that is strictly JSP that outputs JSON and an HTML file that does an AJAX request for that JSON...
subhaze
A: 

Try wrapping the output in the toJson function.

For running it when the DOM is ready try addOnLoad

And if you're wanting to load it via AJAX onLoad try this

[EDIT]

It just dawned on me that I put "toJson" it should be fromJson since you're needing to convert a JSON string to a JSON object. Here is an example dojo: json string to json object

subhaze
@Subhaze, My major concern is how can I retrieve myJSONObj object in dojo, as I am creating and setting in JSP. Any suggestion is highly appreciated.
Rachel