我正在使用 JSF 制作有关乘车共享/销售巴士票的网页。
在某一特定页面上,登录用户可以发布他们的广告(提供或寻找乘车服务)。
他们应该输入以下信息:广告标题、出发城市、目的地城市、出发时间等。
我想要的是,用户获得目的地城市的天气预报显示在弹出窗口 之后 他们点击 提交.
这也意味着我正在使用 openweathermap 等服务。
基本上,我有一个 h:form
和 h:commandButton
,如下所示:
<h:commandButton value="Publish" action="#{adBean.publishAd}" type="submit" onclick="showPopup()">
</h:commandButton>
问题是我不知道如何传递bean值
<h:inputText value="#{adBean.ad.destinationCity}"/>
到 JavaScript 方法 showPopup()
。
我已经尝试过此操作,但目的地城市结果为空。
<h:commandButton value="Publish" action="#{adBean.publishAd}" type="submit" onclick="showPopup(#{adBean.ad.destinationCity})">
</h:commandButton>
为什么会发生这种情况以及如何将其值传递给 JavaScript 代码?
最佳答案
它是null
,因为它被放入用于JavaScript 的属性(onclick) 中。此类属性在页面显示时“呈现”,而不是在提交时或其他时刻(再次)呈现。那么如果当时初始化为null
,那么从服务器端传输到客户端的是
<button value="Publish" ... onclick="showPopup(null)" />
@BalusC 在 How to invoke a bean action method using a link? The onclick does not work 中对此的引用:
In JSF, only the attributes which interpret the EL expression as a
MethodExpression
can be used to declare action methods. All other attributes are interpreted asValueExpression
and they are immediately executed when the HTML output is generated by JSF. This covers theonclick
attribute, whose value should actually represent a JavaScript function.
客户端上的 (h:?)inputText
呈现为纯 html inputText,因此如果您想在提交之前访问它的值(就像我怀疑您想要),您可以在 showPopup
中执行此操作,就像在纯 html/javascript 中一样。
如何做到这一点是 mentioned in many stackoverflow Q/A因此,要么选择最适合您的一个,例如How do I get the value of text input field using JavaScript? ,但请务必阅读 How can I know the id of a JSF component so I can use in Javascript
关于javascript - 如何在表单提交之前将 bean 值传递给 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52297458/