admin管理员组

文章数量:1425195

I have a List of People Objects added to my ModelMap. A person has a name and a date. I know I can access the list by doing the following in the html part of the JSP

 ${peopleList}

However I want to loop through this list in the JSP in a JavaScript tag, I have tried the following but I am having no luck, and for testing I have just been doing an alert.

 var people = "${peopleList}"
 alert(people[0].name);

How can I access these properties in JavaScript.

I have a List of People Objects added to my ModelMap. A person has a name and a date. I know I can access the list by doing the following in the html part of the JSP

 ${peopleList}

However I want to loop through this list in the JSP in a JavaScript tag, I have tried the following but I am having no luck, and for testing I have just been doing an alert.

 var people = "${peopleList}"
 alert(people[0].name);

How can I access these properties in JavaScript.

Share Improve this question asked Apr 23, 2014 at 3:24 sideshowbobsideshowbob 3266 silver badges23 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You are close to the solution, but what you did wrong is a java List object cannot be converted to a javascript list object directly with var people = "${peopleList}". Instead, you can loop through the List object and create the javascript variables manually using JSTL:

Import the jstl core taglib at the top of the jsp:

<%@ taglib uri="http://java.sun./jsp/jstl/core" prefix="c" %>

Then inside the script tag, create your peopleList:

<script type="text/javascript">

var peopleList = new Array();

<c:forEach items="${peopleList}" var="ppl">
    var people = new Object();
    people.name = '${ppl.name}';
    people.date = '${ppl.date}';

    peopleList.push(people);
</c:forEach>

if(peopleList.length > 0){
    alert(peopleList[0].name);
}

</script>

本文标签: springAccessing a ModelMap list through JavaScript in JSPStack Overflow