4

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 here. 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?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
SerotoninChase
  • 424
  • 11
  • 28
  • Related: http://stackoverflow.com/questions/2547814/mixing-jsf-el-in-a-javascript-file/2547908#2547908 (describes for Facelets/JSF, but principles are the same for JSP/JSTL) – BalusC Feb 19 '11 at 02:21

1 Answers1

2

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>
limc
  • 39,366
  • 20
  • 100
  • 145
  • You've got the right idea, but your second example won't work at all because you're setting a single variable, over and over again. It will also break if an address contains a double-quote. – Matt Ball Feb 19 '11 at 01:20
  • @Matt: I made some corrections to my code. The second way should work because the OP wants to pass the value into some javascript function. As for the possible double quote issue in the address, I use fn:replace to replace `"` with `\"`... I think that should work. – limc Feb 19 '11 at 01:28