【问题标题】:using ForEach to loop a JSON array in JSP JSTL使用 ForEach 在 JSP JSTL 中循环一个 JSON 数组
【发布时间】:2018-09-19 10:47:14
【问题描述】:

我正在尝试使用 ForEach 循环遍历从控制器传递过来的 JSON 数组,并为数组中的每个项目创建一个 html 元素。但是,当我尝试运行我的代码时,发生了异常,但浏览器没有指定该错误的确切位置。

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

最后,我想创建一个

循环中每个项目的元素:

 <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>

我是 JSTL 的新手,所以我不确定格式。谁能告诉我我的代码出了什么问题?

【问题讨论】:

  • ${notifications.length-1} 将不起作用。您需要使用${fn:length(notifications)-1}notifications的数据类型是什么?它在您的第一个代码块中看起来像一个集合,但在第二个代码块中看起来像一个字符串。
  • 也许this answer 会帮助你。

标签: arrays jsp foreach jstl


【解决方案1】:

假设notifications 是一个字符串化的 JSON 数组,您可以这样做来创建一个 javascript 对象并使用 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多