How to access a java list coming from the server in javascript inside my jsp
Plz consider the scenario. I have a java class called Person as below:
Person
---------
Integer Id
String name
String address
Now through my spring controller I pass a list of persons to my jsp page(neighbors.jsp) like shown below:
List<Persons> persons = new ArrayList<Person>();
.
.
.
return new ModelAndView("/neighbors").addObject("persons", persons);
Now the problem is her开发者_如何学JAVAe. I have the google maps api in javascript format embedded in neighbors.jsp to display the location of the person logged in. This works fine. Google maps also offer comparison of addresses. I want to display markers of addresses of other persons that are within 5 miles range of user's address. Each of the marker is a link to a page that is going to display that particular person's information.
Suppose I access each address in the following format, how do I call the javascript function?
<c:forEach items="${persons }" var="person">
<!-- I want to pass each address ${person.address} to the javascript functions thats going to compare addresses -->
</c:forEach>
Can someone help me out here on how to handle to scenario?
Two ways to do it:-
First way... you can set the value as a hidden field that allows the javascript to access it:-
<c:forEach items="${persons}" var="person" varStatus="i">
<input id="address${i.count}" type="hidden" value="${person.address}">
</c:forEach>
In your javascript:-
yourJavascriptFunction(document.getElementById("address1").value);
Second way... use <script>
tag in your <c:foreach>
tag:-
<c:forEach items="${persons}" var="person" varStatus="i">
<script>
yourJavascriptFunction("${fn:replace(person.address, "\"", "\\\"")}");
...
</script>
</c:forEach>
精彩评论