sideshowbob
sideshowbob

Reputation: 316

Accessing a ModelMap list through JavaScript in JSP

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.

Upvotes: 1

Views: 6813

Answers (1)

Abhishek Nayak
Abhishek Nayak

Reputation: 3748

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.com/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>

Upvotes: 4

Related Questions