如何将JavaScript变量作为参数传递给JSF动作方法?

时间:2015-02-18 18:36:57

标签: javascript jsf parameter-passing managed-bean

我正在准备JavaScript中的一些变量(在我的具体情况下,我想获得GPS位置):

function getVars() {
    // ...
    var x = locationInfo.lng; 
    var y = locationInfo.lat;
}

我想通过以下命令按钮将它们发送到我的托管bean:

<h:commandButton value="submit" onclick="getVars()" action="#{bean.submit(x,y)}" />
public void submit(int x, int y) {
    // ...
}

如何将xy变量从JavaScript发送到JSF托管bean操作方法?

3 个答案:

答案 0 :(得分: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>
function getVars() {
    // ...
    var x = locationInfo.lng; 
    var y = locationInfo.lat;

    document.getElementById("formId:x").value = x;
    document.getElementById("formId:y").value = y;
}

命令按钮操作方法可以通常的方式将它们作为bean属性访问。

private int x;
private int y;

public void submit() {
    System.out.println("x: " + x);
    System.out.println("y: " + y);
    // ...
}

// Getters+setters.

另一种方法是使用OmniFaces <o:commandScript>PrimeFaces <p:remoteCommand>代替<h:commandButton>。另见a.o. How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?

答案 1 :(得分:3)

如果您使用 PrimeFaces ,您可以使用链接到托管bean的隐藏输入字段,并且可以使用javascript初始化其值,对于PrimeFaces, PF 函数可用于访问链接到隐藏输入的窗口小部件变量,以这种方式:

<script>
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}" />

答案 2 :(得分:-3)

<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}" />

 <script>
        function getVars() {

            var x; 
            var yt;

            x=#{bean.x};
            y=#{bean.y};
        }
    </script>
相关问题