1

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.

1 Answer 1

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.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>
Sign up to request clarification or add additional context in comments.

1 Comment

is c:foreach can put in javascript ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.