如何将JavaScript变量作为参数传递给JSF动作方法? [英] How to pass JavaScript variables as parameters to JSF action method?

查看:173
本文介绍了如何将JavaScript变量作为参数传递给JSF动作方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在准备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 < o:commandScript> PrimeFaces < p:remoteCommand> 而不是< h:commandButton> 。另见a.o. 如何使用本机JavaScript在HTML DOM事件上调用JSF托管bean?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆