如何将 JavaScript 变量作为参数传递给 JSF 动作方法? [英] How to pass JavaScript variables as parameters to JSF action method?
问题描述
我正在用 JavaScript 准备一些变量(在我的特定情况下,我想获取 GPS 位置):
I'm preparing some variables in JavaScript (in my specific case, I'd like to get GPS location):
function getVars() {
// ...
var x = locationInfo.lng;
var y = locationInfo.lat;
}
我想通过以下命令按钮将它们发送到我的托管 bean:
I'd like to send them to my managed bean via the below command button:
<h:commandButton value="submit" onclick="getVars()" action="#{bean.submit(x,y)}" />
public void submit(int x, int y) {
// ...
}
如何将 x
和 y
变量从 JavaScript 发送到 JSF 托管 bean 操作方法?
How can I send x
and y
variables from JavaScript to JSF managed bean action method?
推荐答案
让 JS 将它们设置为相同表单中的隐藏输入值.
Let JS set them as hidden input values in the same form.
<h:form id="formId">
<h:inputHidden id="x" value="#{bean.x}" />
<h:inputHidden id="y" value="#{bean.y}" />
<h:commandButton value="submit" onclick="getVars()" action="#{bean.submit}" />
</h:form>
function getVars() {
// ...
var x = locationInfo.lng;
var y = locationInfo.lat;
document.getElementById("formId:x").value = x;
document.getElementById("formId:y").value = y;
}
命令按钮操作方法可以像通常的方式一样访问它们作为 bean 属性.
The command button action method could just access them as bean properties the usual way.
private int x;
private int y;
public void submit() {
System.out.println("x: " + x);
System.out.println("y: " + y);
// ...
}
// Getters+setters.
另一种方法是使用 OmniFaces
或 PrimeFaces
而不是 <代码>
An alternative is to use OmniFaces <o:commandScript>
or PrimeFaces <p:remoteCommand>
instead of <h:commandButton>
. See also a.o. How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?
这篇关于如何将 JavaScript 变量作为参数传递给 JSF 动作方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!