【发布时间】:2016-09-20 16:08:30
【问题描述】:
我有 3 个文件:
- index.xhtml :我使用 JSF 制作了一个带有提交按钮的 2 字段表单(x:int,y:int)。
- map.js : 包含一个 Js 函数。
- MbZoomtoXy.java : 调用前面的 Js 函数。
我尝试在表单中输入 x 和 y 时。提交按钮应该会给我 x+y 的“警报”。
index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form id="form">
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel for="x-coor" value="X : " />
<p:inputText id="x-coor" value="#{MbZoomtoXy.x}" required="true"/>
<p:outputLabel for="y-coor" value="Y : " />
<p:inputText id="y-coor" value="#{MbZoomtoXy.y}" required="true"/>
</h:panelGrid>
<p:commandButton value="Save" actionListener="#{MbZoomtoXy.save}"/>
</h:form>
</h:body>
</html>
map.js
function zoomToXy(x,y){
var s = x + y;
alert("x+y = "+s);
}
MbZoomtoXy.java
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.context.RequestContext;
@ManagedBean
@SessionScoped
public class MbZoomtoXy {
private MbZoomtoXy() {
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
int x,y;
public MbZoomtoXy(int x, int y) {
this.x = x;
this.y = y;
}
//Here I don t know how to call zoomToXy(x,y) function of map.js
public void save(){
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("...");
}
}
【问题讨论】:
-
您需要将点击处理程序添加到客户端代码中,您不能(实际上)从 Java 中以这种方式调用 JavaScript 函数。给按钮一个 ID 并使用类似 jQuery 的东西来添加一个点击处理程序。您可能需要对 JSF 文件进行一些修改,以防止它立即 POST 回 Java(或在 click 事件上使用 preventDefault)。
-
正如@JeffWatkins 所说,您已经在客户端拥有了输入值。所以试着抓住它们并将它们显示到一个警报对话框中。
标签: javascript java jsf