webtier@glassfish.java.net

Re: f:ajax and javascript events in JSF 2.0

From: <webtier_at_javadesktop.org>
Date: Tue, 02 Mar 2010 11:00:04 PST

Ok, I toyed with it for a couple of minutes. The following works, is you need it:

[b]page.xhtml:[/b]

[code]
<h:commandButton value="Postback">
    <f:ajax render="pnl" />
</h:commandButton>

<h:panelGroup id="pnl" layout="block">
    <script type="text/javascript">
        #{bean.scriptSnippet}
    </script>
</h:panelGroup>
[/code]

[b]Bean.java[/b]

[code]
@RequestScoped
@Named
public class Bean {
    public String getScriptSnippet() {
        System.out.println(getClass().getSimpleName() + ".getScriptSnippet()");
        FacesContext ctx = FacesContext.getCurrentInstance();
        return ctx.getPartialViewContext().isAjaxRequest() ?
                      "alert('script in ajax response')" :
                      "alert('script snippet')";
    }
}
[/code]

So, essentially, you can dynamically generate a script and send it to the client. It will be executed there.

Probably, there's a better way, but, until somebody answers and gives us the better way, this should do.

Here's the Ajax response I got from the server:

[code]
<?xml version="1.0" encoding="utf-8"?>
<partial-response><changes><update id="pnl"><![CDATA[<div id="pnl">
                <script type="text/javascript">
                    alert('script in ajax response')
                </script></div>]]></update><update id="javax.faces.ViewState"><![CDATA[-258594229912227434:4449133574477870584]]></update></changes></partial-response>
[/code]

Hope this helps.
[Message sent by forum member 'vesuvius' (vesuvius_prime_at_hotmail.com)]

http://forums.java.net/jive/thread.jspa?messageID=389671