How to use model attribute of a JSP into javascript?

0 votes
asked Sep 13, 2017 by jaybee

Controller:

List<SampleModel> data = service.getdata();

model.addAttribute("modeldata",data);
return "jsp";

Is there a way to easily access/use the model attribute of a jsp in a javascript function? I tried accessing it in a loop but there's no result.

Sample:

 <script type="text/javascript">
 $(document).ready(function() {
   sampleFunction();
 });

 sampleFunction() {
   for (i=0;i<=10;i++) {

     console.log(${modeldata[i].sampledatapath});

   }
 }

 </script>

Thanks!

1 Answer

0 votes
answered Mar 1, 2018 by devgo

You can use following:

<script type="text/javascript">

    $(document).ready(function() {
        sampleFunction();
    });

    function sampleFunction(){  
        <c:forEach var="model" items="${modeldata}">
            console.log("${model.sampledatapath}"); 
        </c:forEach>
    }

</script>
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...