在 JavaScript 中从支持 bean 迭代列表
我有一个支持 bean 中的对象列表 我想用 JavaScript 迭代它, 所以我尝试了以下操作:
<script>
//<![CDATA[
var length = #{fn:length(myBean.myList)};
for (i = 0; i <= length; i++) {
var value = '#{myBean.myList[i].id}';
var label = '#{myBean.myList[i].firstName}';
alert(value);
alert(label);
}
//]]>
</script>
我在控制台中没有收到任何错误,但它显示空警报。这是如何引起的以及如何解决?
I have a list of objects in backing bean
and I would like to iterate over it in JavaScript,
so I tried the following:
<script>
//<![CDATA[
var length = #{fn:length(myBean.myList)};
for (i = 0; i <= length; i++) {
var value = '#{myBean.myList[i].id}';
var label = '#{myBean.myList[i].firstName}';
alert(value);
alert(label);
}
//]]>
</script>
I get no errors in console, but it shows empty alerts. How is this caused and how can I solve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要先将其转换为 JS 对象数组。假设
id
是数字,具体方法如下:仅当用户名包含换行符(双引号已被 JSF 转义)时,此操作才会失败。考虑按照 Escape JavaScript in Expression Language 显式转义 JS
更好的方法是让 JSF (或者最好是一些 Web 服务,例如 JAX-RS,在 ajax 请求时)已经使用 JSON 格式返回它一个 JSON像 Google Gson 这样的解析器/格式化程序,这样你就可以这样做:
with (假设你正在使用Gson):
另请注意,您应该使用
i <长度
不是i <= 长度
。另请注意,users
比myList
更具自记录性。You need to convert it to an array of JS objects first. Provided that
id
is numeric, here's how:This will only fail if the user name contains a newline (double quotes are already escaped by JSF). Consider explicitly escaping JS as per Escape JavaScript in Expression Language
Better way is to let JSF (or preferably, some web service, e.g. JAX-RS, upon an ajax request) return it in JSON format already by using a JSON parser/formatter like Google Gson, so that you can just do:
with (assuming that you're using Gson):
Please also note that you should use
i < length
noti <= length
. Please also note thatusers
is more self-documenting thanmyList
.我遇到了同样的错误,我通过使用解决了它
“<”
而不是 <在 for 循环中I faced the same error and I resolved it by using
"<"
instead of < in for loop