You need to convert it to an array of JS objects first. Provided that id
is numeric, here's how:
var users = [
<ui:repeat value="#{bean.users}" var="user" varStatus="loop">
{ id: #{user.id}, firstName: "#{user.firstName}" }#{loop.last ? '' : ','}
</ui:repeat>
];
for (var i = 0; i < users.length; i++) {
var user = users[i];
alert(user.id);
alert(user.firstName);
}
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:
var users = #{bean.usersAsJson};
for (var i = 0; i < users.length; i++) {
var user = users[i];
alert(user.id);
alert(user.firstName);
}
with (assuming that you're using Gson):
public String getUsersAsJson() {
return new Gson().toJson(users);
}
Please also note that you should use i < length
not i <= length
. Please also note that users
is more self-documenting than myList
.
#
things are meant to be executed on the server side, while your loop and itsi
variable is on the client. – Phenobarbital