javascript - 如何在表单提交之前将 bean 值传递给 JavaScript

标签 javascript forms jsf managed-bean commandbutton

我正在使用 JSF 制作有关乘车共享/销售巴士票的网页。
在某一特定页面上,登录用户可以发布他们的广告(提供或寻找乘车服务)。
他们应该输入以下信息:广告标题、出发城市、目的地城市、出发时间等。

我想要的是,用户获得目的地城市的天气预报显示在弹出窗口 之后 他们点击 提交.
这也意味着我正在使用 openweathermap 等服务。

基本上,我有一个 h:formh: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 as ValueExpression and they are immediately executed when the HTML output is generated by JSF. This covers the onclick 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/

相关文章:

javascript - ESLint 不会破坏 Github Actions 的构建

javascript - 单击后退按钮时如何保留表单数据

eclipse - 方法必须具有签名 "String method()"但具有签名 "void method()"

javascript - 如何在使用 Primefaces 的 Gmap 中准备好 map 后运行 js 函数?

javascript - React hook 状态对于几个相同的事件具有不同的值

javascript - 无法使用 setTimout 在小书签中不起作用

html - 是否允许输入没有值?

Facelets 中未定义 Javascript 方法

javascript - 获取 Div 宽度然后更新范围变量

ios - Xamarin.Forms iOS UIKit.UIImage 错误