I have stored a bulk of objects in an ArrayList and I have set that in the request. Now I want to retrive the values in the Arraylist from my java script. Please help me with the solution
+3
A:
You can use JSON to facilitate the exchange of information between Java and Javascript. Libraries are available on both ends.
To put the elements of a List
into an array, you can use Collection.toArray
.
polygenelubricants
2010-06-14 11:15:35
+1
A:
You need to serialize them as javascript first. There are 2 ways to do it:
1) Universal way - http://stackoverflow.com/questions/338586/a-better-java-json-library You just put in your jsp something like this:
<script...>
var myArray = <% JSON.Serialize(myArray) %>;
</script>
2) Fast and dirty:
<script...>
var myArray = [
<c:forEach items="${myArray}" var="item">
{
name = "<c:out value="${item.name}">",
text = "<c:out value="${item.text}">"
},
</c:forEach>
];
</script>
Both will result in Javascript like this, and can be used in JS:
var myArray = [
{
name = "Mike",
text = "Hello world"
},
{
name = "Max",
text = "Hi!"
}
];
Max
2010-06-14 11:21:32
I have to mention that I would not recommend using JSON for simple arrays (arrays of strings, integers) as it is much easier to do in the "dirty way" with same result, and even better performance.However, if you have some complex objects that have to be passed to JavaScript - JSON serialization is a way to go.
Max
2010-06-14 11:26:42