0

I am trying to use a ForEach loop to iterate through my JSON array passed over from the controller and create a html element for each item in the array. However when i try to run my code, an exception occurred but the browser did not specify where exactly is that error.

   <c:forEach var = "i" begin = "0" end = '${notifications.length-1}'>
                Item <c:out value = "${i}"/><p>
            </c:forEach>    

Eventually, I want to create a

element for each item in the loop:

 <c:set var = "temp" value = "${notifications}"/>
           <c:set var = "string1" value = "${fn:substring(temp, 0, 16)}" />
          <p class="alert alert-info" data-toggle="tooltip" title='${notifications}'><strong>Info!</strong> ${string1 }...</p>

I am new to JSTL so I am not sure about the format. Would anyone be able to tell me what went wrong with my code ?

purplewind
  • 331
  • 10
  • 26
  • `${notifications.length-1}` will not work. You need to use `${fn:length(notifications)-1}`. What is the data type of `notifications`? It looks like a collection in your first code block, but a string in the second. – Matt Sep 19 '18 at 15:43
  • Maybe [this answer](https://stackoverflow.com/a/5977675/2751039) will help you. – Matt Sep 19 '18 at 15:50

1 Answers1

0

Assuming notifications is a stringified JSON array, you could do something like this to create a javascript object and append the elements with jquery.

<script>
var json = JSON.parse('${notifications}');

$(document).ready(function() {
    for (var i in json) {
        $('body').append('<p class="alert alert-info" data-toggle="tooltip"><strong>Info!</strong> ' + json[i] + '</p>');
    }
});
</script>
Matt
  • 828
  • 8
  • 25