使用jQuery中的参数调用JSF托管bean方法

4 javascript jquery jsf jsf-2

我正在使用JSF来构建一个站点.我在我的主页上添加了jQuery Gritter(Growl)通知.是否有可能调用内部的一个管理bean方法before_close:$.gritter.add功能?

我想要使​​用的代码如下:

<h:body>
    <c:forEach items="#{notificationBean.growlNotificationList}" var="p">
        <script>
        /* <![CDATA[ */
        $.gritter.add({
            // (string | mandatory) the heading of the notification
            title: 'Notification',
            // (string | mandatory) the text inside the notification
            text: 'Comment on your staus',
            // (bool | optional) if you want it to fade out on its own or just sit there
            sticky: true, 
            // (int | optional) the time you want it to be alive for before fading out (milliseconds)
            time: 8000,
            // (string | optional) the class name you want to apply directly to the notification for custom styling
            class_name: 'gritter-light',
            // (function | optional) function called before it closes
            before_close: function(e, manual_close){
                '#{notificationBean.set0ToGrowlToShow(p.notificationID)}'
            }
        });
        /* ]]> */
        </script>
    </c:forEach>
</h:body>
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 5

您当前的尝试只是将给定的EL表达式解释为值表达式,并在生成嵌入了JS代码的HTML输出时立即打印其结果.就像你在使用它一样<h:outputText>.这确实无法奏效.

然而,理解功能要求.标准JSF API不提供现成的解决方案.如果您想坚持使用标准的JSF API,最好的办法是创建一个隐藏的表单,其中包含一个使用JavaScript触发的隐藏命令链接.

基本上,

<h:form id="form" style="display:none">
    <h:inputHidden id="id" value="#{notificationBean.notificationID}" />
    <h:commandLink id="command" action="#{notificationBean.set0ToGrowlToShow}">
        <f:ajax execute="@form" />
    </h:commandLink>
</h:form>
Run Code Online (Sandbox Code Playgroud)

$("[id='form:id']").val(#{p.notificationID});    
$("[id='form:command']").click();
Run Code Online (Sandbox Code Playgroud)

但是,这非常笨拙.考虑寻找第三方JSF组件甚至实用程序库来实现该要求.JSF实用程序库OmniFaces具有此<o:commandScript>组件.另请参见其展示页面.

<h:form>
    <o:commandScript name="set0ToGrowlToShow" action="#{notificationBean.set0ToGrowlToShow}" />
</h:form>
Run Code Online (Sandbox Code Playgroud)

set0ToGrowlToShow(#{p.notificationID});
Run Code Online (Sandbox Code Playgroud)

(请注意,这是设置为HTTP请求参数,而不是作为操作方法参数)

JSF组件库PrimeFaces具有与<p:remoteCommand>此非常相似的功能<o:commandScript>.另请参见其展示页面.更重要的是,PrimeFaces有一个随时可用的<p:growl>组件,它与你的jQuery插件基本相同!另请参见其展示页面.你可以做的不是你的整个jQuery事情:

<p:growl globalOnly="true" autoUpdate="true" />
Run Code Online (Sandbox Code Playgroud)

并通过消息提供它

facesContext.addMessage(null, message);
Run Code Online (Sandbox Code Playgroud)

也可以看看:

  • 是.你熟悉基本的HTML吗?只需在浏览器中右键单击*查看源*即可.您只需要确保JSF生成的HTML代码是[有效](http://validator.w3.org). (2认同)
  • 这是与具体问题无关的另一个问题.答案基本上已经在异常消息本身中:只是不要在多个组件上使用相同的ID. (2认同)
  • 如上所述,这将非常笨拙.您可以添加另一个循环,使用动态ID打印表单.你可以使用一个带有附加`<h:inputHidden>`的表单,你用jQuery操作它的值.我用后一种方法编辑了答案. (2认同)