Reputation: 985
I have a java code which i made by using MyEclipse. In the main method I have an output which is an array [10,23,31,45]. My Question is how can i get these values in java script array. Is there any ways or tools through which i can use my java object values in java script to display something in HTML.
Thanks In advance.
Upvotes: 0
Views: 1454
Reputation: 88727
Well, that depends on how you create your html pages or generally get data onto your page. In most frameworks you could render the array directly into the hmtl source which is delivered to the browser.
In a JSP it might be something like this:
<script ...>
var myarray = <%=Arrays.toString(javaArray)%> <!-- not sure about the formatting though, might have to be altered-->
</srcipt>
Edit
To clarify: what you need is a string representation of your array that fits JavaScript, and toString()
might not result in what you need. In that case you could either use a JSON library to convert your objects to JSON (and thus a JavaScript compatible represenation) or write your own array/object -> string converter.
Using the above code with int[] javaArray = {1,2,3};
would result in var myarray = [1, 2, 3];
Upvotes: 2
Reputation: 49402
If you want to execute javascript from within java in the JVM , this might be of help : http://commons.apache.org/bsf/
If you want to output java object values in JSP , you can use EL , scriptlets , expressions etc .
Expression: var javascriptArray = <%= javaArray.toString() %>
EL: var javascriptArray = ${javaArray}
(mind the formatting in this case)
JSTL: var javascriptArray = [
<c:forEach var="element" items="${javaArray}" varStatus="cursor">
"${element}"
<c:if test="${!cursor.last}">,</c:if>
</c:forEach>
]
Upvotes: 1