Bub*_*ble 16 javascript jsf parameter-passing managed-bean
我正在准备JavaScript中的一些变量(在我的具体情况下,我想获得GPS位置):
function getVars() {
// ...
var x = locationInfo.lng;
var y = locationInfo.lat;
}
Run Code Online (Sandbox Code Playgroud)
我想通过以下命令按钮将它们发送到我的托管bean:
<h:commandButton value="submit" onclick="getVars()" action="#{bean.submit(x,y)}" />
Run Code Online (Sandbox Code Playgroud)
public void submit(int x, int y) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
如何将JavaScript x和y变量从JavaScript 发送到JSF托管bean操作方法?
Bal*_*usC 27
让JS将它们设置为相同形式的隐藏输入值.
<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>
Run Code Online (Sandbox Code Playgroud)
function getVars() {
// ...
var x = locationInfo.lng;
var y = locationInfo.lat;
document.getElementById("formId:x").value = x;
document.getElementById("formId:y").value = y;
}
Run Code Online (Sandbox Code Playgroud)
命令按钮操作方法可以通常的方式将它们作为bean属性访问.
private int x;
private int y;
public void submit() {
System.out.println("x: " + x);
System.out.println("y: " + y);
// ...
}
// Getters+setters.
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用OmniFaces <o:commandScript>或PrimeFaces <p:remoteCommand>而不是<h:commandButton>.另请参阅ao 如何使用本机JavaScript在HTML DOM事件上调用JSF托管bean?
如果使用PrimeFaces,则可以使用链接到托管 bean 的隐藏输入字段,并且可以使用 javascript 初始化其值,对于 PrimeFaces,PF函数可用于访问链接到隐藏输入的小部件变量,以这种方式:
<script type="text/javascript">
function getVars() {
// ...
var x = locationInfo.lng;
var y = locationInfo.lat;
PF('wvx').jq.val( lat1 );
PF('wvy').jq.val( lng1 );
}
</script>
<p:inputText type="hidden" widgetVar="wvx" value="#{bean.x}" />
<p:inputText type="hidden" widgetVar="wvy" value="#{bean.y}" />
Run Code Online (Sandbox Code Playgroud)