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.1k views
in Technique[技术] by (71.8m points)

jsf 2 - How to pass backing bean value to JavaScript?

I would like to read the backing bean value in JSF and then pass over to JavaScript, may I know how this can be done?

Backing bean sample code:

@ManagedBean(name="enquiry")
@SessionScoped
public class Enquiry {

  public boolean noQuery;

  /** getter and setter **/
}

In XHTML sample code, I would like pass the backing bean value and then pass into showNoQueryPrompt() like this:

<h:commandLink onClick="showNoQueryPrompt(#{enquiry.noQuery})">
</h:commandLink>

And then in JavaScript code, I can read the boolean value to determine whether I should prompt or not prompt. Here is the code:

<script ...>
   var showNoQueryPrompt(Boolean showPrompt) {

     if( showPrompt == "true" ) {
        alert('No query');
     }
   }
</script>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

To the point, you need to understand that JSF merely produces HTML code and that JS is part of HTML. So all you need to do is to write JSF/EL code accordingly that it produces valid HTML/JS code. Indeed, using EL to inline bean properties in the generated JavaScript code like as in your attempt is one of the right ways.

Assuming that this is indeed the real code, you however made some syntax mistakes. The onClick attribute is invalid. It must be in all lowercase. Otherwise JSF simply won't render the attribute at all.

<h:commandLink value="link" onclick="showNoQueryPrompt(#{enquiry.noQuery})" />

JavaScript has no notion of strong typing. The Boolean type in function argument is invalid. Remove it. Otherwise you will face a nice JS syntax error (in browser's JS console).

function showNoQueryPrompt(showPrompt) {
   if (showPrompt) {
      alert('No query');
   }
}

Note that I expect that you understand that this runs before commandlink's own action is been invoked (you should now have understood; JSF generates HTML; rightclick page in browser and View Source to see it yourself). But you didn't cover that in your concrete question (even more, you didn't describe the concrete problem with the given code in the question at all), so I can't give an detailed answer on that.


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

...