遍历字符串列表时在 jsp 中出错
Getting error in jsp while traversing list of string
我正在从我的控制器发送一个字符串列表到我的 jsp
model.addAttribute("itemList", Arrays.asList("first", "second"));
并试图将它们放入我的 jsp
<c:forEach var="singleItem" items="${itemList}">
console.log(${singleItem});
</c:forEach>
但我收到以下错误
jQuery.Deferred exception: first is not defined
ReferenceError: first is not defined
console.log
接受一个字符串。 JS 在服务端渲染,运行 在客户端渲染。 ${singleItem}
需要是:
- 引号
- JS 转义
查看您呈现的页面:您会看到
console.log(first);
console.log(second);
JS 认为那些是变量引用(因为在 JS 中,它们是)。
仅仅用引号括起来是不够的,因为被呈现的字符串可能有它自己的引号,例如
Arrays.asList("first's doodad")
没有JS转义,使用JS单引号:
console.log('${singleItem}');
将呈现为:
console.log('first's doodad');
这是无效的 JS。
了解代码的位置 运行 并了解检查呈现的 HTML 很重要。渲染到一个环境中时,了解您要渲染到的环境很重要,就像将 HTML 渲染到 HTML.
中一样
我正在从我的控制器发送一个字符串列表到我的 jsp
model.addAttribute("itemList", Arrays.asList("first", "second"));
并试图将它们放入我的 jsp
<c:forEach var="singleItem" items="${itemList}">
console.log(${singleItem});
</c:forEach>
但我收到以下错误
jQuery.Deferred exception: first is not defined
ReferenceError: first is not defined
console.log
接受一个字符串。 JS 在服务端渲染,运行 在客户端渲染。 ${singleItem}
需要是:
- 引号
- JS 转义
查看您呈现的页面:您会看到
console.log(first);
console.log(second);
JS 认为那些是变量引用(因为在 JS 中,它们是)。
仅仅用引号括起来是不够的,因为被呈现的字符串可能有它自己的引号,例如
Arrays.asList("first's doodad")
没有JS转义,使用JS单引号:
console.log('${singleItem}');
将呈现为:
console.log('first's doodad');
这是无效的 JS。
了解代码的位置 运行 并了解检查呈现的 HTML 很重要。渲染到一个环境中时,了解您要渲染到的环境很重要,就像将 HTML 渲染到 HTML.
中一样