Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

jsf - Iterate over a list from backing bean in JavaScript

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...