如何将JSF托管bean属性传递给JavaScript函数? [英] How do I pass JSF managed bean properties to a JavaScript function?

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

问题描述

我想知道如何将JSF托管bean属性传递给JavaScript函数。

I would like to know how I can pass JSF managed bean properties to a JavaScript function.

这样的事情:

<script>
  function actualizaMenu(key){
    #{linkedMenu.setKey(key)}
  }
</script>





<ul>
  <ui:repeat value="#{moduleList.modulos}" var="entity">
    <li>
      <a onclick="actualizaMenu(#{entity.key})">#{entity.nombre}</a>
    </li>
  </ui:repeat>
</ul>


推荐答案

这并不完全是传递JSF变量。这只是打印JSF变量,就像它们是JavaScript变量/值一样。你知道,JSF和JS根本没有同步运行。 JSF在webserver中运行并生成HTML / CSS / JS代码,这些代码一旦到达那里就会在webbrowser中运行。

This is not exactly "passing" of JSF variables. This is just printing JSF variables as if they are JavaScript variables/values. You know, JSF and JS do not run in sync at all. JSF runs in webserver and produces HTML/CSS/JS code which in turn runs in webbrowser once arrived over there.

您的具体问题很可能是因为您编写了JSF代码以这种方式生成无效的JS语法。验证这一点的简单方法是只检查JSF生成的HTML输出,您可以通过右键单击,浏览器中的查看源找到,并检查是否在文档中看不到任何语法错误报告。浏览器中的JS控制台,您可以在Chrome / IE9 + / Firefox23 +中按F12找到。

Your concrete problem is most likely caused because you wrote JSF code in such way that it generates invalid JS syntax. An easy way to verify that is by just checking the JSF-generated HTML output which you can find by rightclick, View Source in browser, and by checking if you don't see any syntax error reports in the JS console in browser which you can find by pressing F12 in Chrome/IE9+/Firefox23+.

想象一下#{entity.key} 这里

<a onclick="actualizaMenu(#{entity.key})">#{entity.nombre}</a>

打印一个Java字符串变量,如foo,然后生成的HTML看起来像

prints a Java string variable like "foo", then the generated HTML would look like

<a onclick="actualizaMenu(foo)">some name</a>

但是,嘿,看,这代表一个名为<$> c的JavaScript 变量 $ c> foo ,而不是JS字符串值!所以如果你真的想最终以

But hey, look, that represents a JavaScript variable named foo, not a JS string value! So if you actually want to ultimately end up as

<a onclick="actualizaMenu('foo')">some name</a>

然后你应该指示JSF生成那个HTML:

then you should instruct JSF to generate exactly that HTML:

<a onclick="actualizaMenu('#{entity.key}')">#{entity.nombre}</a>

请注意JSF变量中的特殊字符。您可以使用 OmniFaces :escapeJS() function 为此。

Beware of special characters in the JSF variable though. You can use OmniFaces of:escapeJS() function for that.

无关具体问题,具体实施 actualizaMenu()毫无意义。您似乎正在尝试设置bean属性。您不应该使用JS,而是使用< h:commandLink>

Unrelated to the concrete problem, the concrete implementation of actualizaMenu() makes no sense. You seem to be attempting to set a bean property. You should not use JS for that, but a <h:commandLink> instead.

<h:commandLink value="#{entity.nombre}" action="#{linkedMenu.setKey(entity.key)}" />

如果需要,可以使用< f:ajax> 使其异步。

Nest if necessary a <f:ajax> to make it asynchronous.

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

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