简体   繁体   English

如何在我的jsp中的javascript中访问来自服务器的Java列表

[英]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的Java类,如下所示:

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: 现在,通过我的spring控制器,将人员列表传递到我的jsp页面(neighbors.jsp),如下所示:

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. 我在neighbors.jsp中嵌入了javascript格式的google maps api,以显示登录人员的位置。这很好。 Google maps also offer comparison of addresses. Google地图还提供地址比较。 I want to display markers of addresses of other persons that are within 5 miles range of user's address. 我想显示位于用户地址5英里范围内的其他人的地址标记。 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? 假设我以以下格式访问每个地址,该如何调用javascript函数?

<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:- 第一种方式 ...您可以将值设置为允许javascript访问的隐藏字段:-

<c:forEach items="${persons}" var="person" varStatus="i">
   <input id="address${i.count}" type="hidden" value="${person.address}">
</c:forEach>

In your javascript:- 在您的javascript中:-

yourJavascriptFunction(document.getElementById("address1").value);

Second way ... use <script> tag in your <c:foreach> tag:- 第二种方式 ...在<c:foreach>标记中使用<script> <c:foreach>标记:-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM