How to access java list coming from server in javascript inside my jsp

Plz consider the scenario. I have a java class called Person, as shown below:

Person --------- Integer Id String name String address 

Now, through my spring controller, I pass the list of people to my jsp page (neighbors.jsp), as shown below:

 List<Persons> persons = new ArrayList<Person>(); . . . return new ModelAndView("/neighbors").addObject("persons", persons); 

Now the problem is here. I have google maps api in javascript format built into neighbors.jsp to display the location of a registered user. This works great. Google Maps also offers address comparisons. I want to display the address markers of other persons that are within 5 miles of the user's address. Each of the markers is a link to a page that will display this information for a specific person.

Suppose I access each address in the following format, what can I call a 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 here how to handle the script?

+4
source share
1 answer

Two ways to do this: -

The first way ... you can set the value as a hidden field that allows 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 the <script> tag in the <c:foreach> : -

 <c:forEach items="${persons}" var="person" varStatus="i"> <script> yourJavascriptFunction("${fn:replace(person.address, "\"", "\\\"")}"); ... </script> </c:forEach> 
+2
source

Source: https://habr.com/ru/post/1340407/


All Articles