【问题标题】:Can not call backing bean method from javascript无法从 javascript 调用支持 bean 方法
【发布时间】:2014-02-10 15:43:09
【问题描述】:

我尝试用 bean 方法编写 javascript 代码。我在应用程序启动时成功了。

当我运行我的应用程序时,js 函数调用 bean 方法并返回值,但是当我单击按钮时,它不再调用。我的意思是,它只在应用程序启动时调用 bean 方法。 我的按钮是:

<p:commandLink oncomplete="myRemote();" title="my button"
               />

我的javascript函数是:

 function myRemote() {
 ${myBackingBean.actionMyValues()}

 }

我的 Bean 是:

@Controller
@Scope("view")
public class MyBackingBean implements Serializable {


public String actionMyValues() {

    String js="";
    /*getting some values from database and adding it to javascript variables.*/
    js += "alert('alert')";//
    return js;
}
}

【问题讨论】:

  • 这个问题我不清楚,但你为什么不考虑使用 p:remoteCommand ?
  • 我的设计就像将客户端中的javascript代码编写为字符串并将其传递给客户端。当应用程序运行时,这工作一次。但是,如果我尝试通过单击按钮来执行此操作,则 javascript 函数的内容不会改变。 js函数没有调用bean方法,所以没有获取到字符串的新内容。

标签: java javascript spring jsf primefaces


【解决方案1】:

如果你想从你的 backing bean 调用 JS,你可以使用 org.primefaces.context.RequestContext 类:

String js="";
/*getting some values from database and adding it to javascript variables.*/
js += "alert('alert')";
RequestContext.getCurrentInstance().execute("js");

编辑

正如 cmets 中所建议的,您也可以使用 p:remoteCommand (https://www.primefaces.org/showcase/ui/ajax/remoteCommand.xhtml)

远程命令将替换您的自定义 JS 函数:

<p:commandButton value="My button" type="button" onclick="myRemote()" id="btnRemote" />  

<p:remoteCommand name="myRemote" actionListener="#{myBackingBean.actionMyValues()}"/>   

那么如果你需要从你的bean调用JS你仍然需要使用RequestContext

【讨论】:

  • 据我所知,问题是另一种方式,从JS调用服务器端方法。
  • 确实,但是在提议的代码中,从服务器端执行 JS 的部分是错误的。我制作并编辑,更好的解决方案是用 Hatem 建议的 p:remoteCommand 替换整个东西
  • 这是另一个问题\
猜你喜欢
  • 1970-01-01
  • 2011-04-04
  • 2012-11-27
  • 1970-01-01
  • 2014-02-16
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多