Reputation: 1235
I have hard-coded data into a .jsp file. What I want to do is populate a JavaScript array with data sent from the server.
I have tried to send the data from another .jsp page, but I cannot figure out how to convert it into a JavaScript var for me to be able to use it in my page, I also have started using JSON objects, but before I continue I just need some guidance on what the best way to do this would be.
That is: populate a JavaScipt array on a .html or .jsp file from the server. The array will then be used for Google Maps API.
Let me know if you have any questions:
thanks
Upvotes: 2
Views: 2874
Reputation: 1108577
If it's hardcoded, why not making it a JS variable directly?
var foo = [{
"name1": "value1a",
"name2": "value2a"
},{
"name1": "value1b",
"name2": "value2b"
}];
Or if it's hardcoded in Java side and you intend to use it in JS side as well, then convert the Java object to JSON using one of the many JSON serializers/parsers available. At the bottom of json.org you can find an overview of all available JSON APIs in Java. One of them is Google Gson. It's able to convert for example a List<SomeBean>
to a JSON string as follows
String jsonString = new Gson().toJson(someBeans);
You can then just let JSP print it as if it's a JS variable, assuming that it's stored as a request attribute:
var foo = ${jsonString};
Upvotes: 3
Reputation: 328556
This is pretty simple:
<script>
tag (i.e. the JSP needs to be accessible with a URL; put that URL into the src
attribute).Example for the JSP code:
var data = [<% ...generate array elements here... %>];
That will allow you to access the variable data
in all JavaScript that is executed afterwards. In your case, you will include the script as the first thing in the page so every other script can use it.
Neat trick: Add a query parameter to specify the variable name:
var <%=request.getParameter("name") %> = [<% ...generate array elements here... %>];
and include it with
<script src="...url...?name=data" type="text/javascript">
Upvotes: 1