How could I iterate the values in ArrayList in java from java script?
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
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
.
You need to serialize them as javascript first. There are 2 ways to do it:
1) Universal way - https://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!"
}
];
精彩评论