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?
You need to convert it to an array of JS objects first. Provided that
idis 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 < lengthnoti <= length. Please also note thatusersis more self-documenting thanmyList.