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

查看:30
本文介绍了如何将 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) {
    // ...
}

如何将 xy 变量从 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 而不是 <代码>.另见 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天全站免登陆