如何将支持bean值传递给JavaScript? [英] How to pass backing bean value to JavaScript?

查看:358
本文介绍了如何将支持bean值传递给JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JSF中读取backing bean值,然后传递给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?

支持bean示例代码:

Backing bean sample code:

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

  public boolean noQuery;

  /** getter and setter **/
}

在XHTML示例代码中,我想传递支持bean值,然后传递到 showNoQueryPrompt(),如下所示:

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>

然后在JavaScript代码中,我可以读取布尔值来确定是否应该提示或不提示。以下是代码:

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>


推荐答案

到目前为止,您需要了解JSF仅仅是生成HTML代码,JS是HTML的一部分。所以你需要做的就是相应地编写JSF / EL代码,它生成有效的HTML / JS代码。实际上,使用EL在生成的JavaScript代码中内联bean属性就像在你的尝试中一样是正确的方法。

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.

假设这确实是真实的代码,但是你犯了一些语法错误。 onClick 属性无效。它必须全部小写。否则JSF根本不会呈现该属性。

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没有强类型的概念。函数参数中的 Boolean 类型无效。去掉它。否则你将面临一个不错的JS语法错误(在浏览器的JS控制台中)。

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');
   }
}

请注意,我希望您了解此操作之前命令链接自己的动作已被调用(您现在应该已经理解; JSF生成HTML;在浏览器中右键单击页面并查看源自己看看)。但是你没有在你的具体问题中讨论这个问题(更多的是,你根本没有用问题中的给定代码描述具体问题),所以我不能就此给出详细的答案。

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.

这篇关于如何将支持bean值传递给JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆