简体   繁体   中英

How to pass JavaScript variables as parameters to JSF action method?

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;
}

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) {
    // ...
}

How can I send x and y variables from JavaScript to JSF managed bean action method?

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;
}

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.

An alternative is to use OmniFaces <o:commandScript> or PrimeFaces <p:remoteCommand> instead of <h:commandButton> . See also ao How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?

If you use PrimeFaces , you can use a hidden input field linked to a managed bean, and you can initialize its value using javascript, for PrimeFaces, the PF function can be used to access a widget variable linked to the hidden input, in this way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM