使用javascript参数对ajax回调进行Primeface

Mih*_*ban 4 javascript ajax primefaces

我正在努力将Primefaces bean属性直接发送到javascript,以便打开一个新页面并将bean属性的内容写入新页面.

我正在使用Primefaces 4.0.

我有一个这样的命令按钮:

 <p:commandButton id="buttonId" update="buttonId, otherComponentId"
    value="press me" process="@this" actionListener="#{homeController.myMethod}"
    oncomplete="handleComplete(xhr, status, args)">
 </p:commandButton>
Run Code Online (Sandbox Code Playgroud)

在handleComplete中,javascript函数args未定义,但不是xhr和status.javascript函数定义:

function handleComplete(xhr, status, args){
    var w = window.open();
    w.document.open();
    alert(xhr.responseText.substring(100));
    alert(status);
    alert(args);
    var d = '<head></head><body>'+ args.firstParam +'<body>';
    w.document.write(d);
    w.document.close();
}
Run Code Online (Sandbox Code Playgroud)

首先警告它给我页面,第二个解析错误,错误是:Uncaught TypeError:无法读取未定义的属性'firstParam'

我想在args中传入一个这样的字符串:

public String MyMethod() {
    RequestContext context = RequestContext.getCurrentInstance();  
    context.addCallbackParam("firstParam", "my string");
      return "";
}
Run Code Online (Sandbox Code Playgroud)

并使用javascript访问它args.firstParam.

该方法被调用,(我有一些工作的打印屏幕.)

我必须尝试这种方式,而不是将文本设置为

<h:outputText id="myText" escape="false" rendered="true"
            value="#{homeController.property}" />
Run Code Online (Sandbox Code Playgroud)

然后得到这个元素的innerHTML,因为我将使用innerHTML获得的内容与bean中的字符串变量不同.这种方法有效但不是我想要的.我想知道为什么args对象是未定义的,或者我怎样才能从javascript中管理bean属性.谢谢.

Hat*_*mam 5

首先,你应该确保调用你的方法.如果正确调用了方法,请进行一些日志记录或调试方法.

如果不是,您可能希望将process属性添加到按钮中,并将进程设置为@this.

如果在此阶段调用了您的方法,那么您的页面中会出现验证错误.

我会在actionListener中调用我的方法而不是在行动中,并将()放在最后.action和actionListener之间的差异

请尝试以下方法

<p:commandButton id="buttonId"
 value="press me"  actionListener="#{homeController.myMethod()}"
 process="@this"
 oncomplete="handleComplete(xhr, status, args)">
</p:commandButton>
Run Code Online (Sandbox Code Playgroud)

由于您的错误是"firstParam"未定义且未定义"args",您可能需要确保firstParam值不为null!