3

As response to an Ajax-request I want to return Javascript that is executed on the client immediately. I tried it like this but it doesn't work:

<html xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html">
<h:head></h:head>
<h:body>
    <h:form>
        <h:commandButton value="js">
            <f:ajax event="click" listener="#{myBean.js}"/>
        </h:commandButton>
    </h:form>
</h:body>
</html>

the bean:

package mypackage;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialResponseWriter;
import javax.inject.Named;

@Named
public class MyBean {

    public void js() {
        System.out.println("called");
        FacesContext ctx = FacesContext.getCurrentInstance();
        ExternalContext extContext = ctx.getExternalContext();
        if (ctx.getPartialViewContext().isAjaxRequest()) {
            try {
                extContext.setResponseContentType("text/xml");
                extContext.addResponseHeader("Cache - Control ", "no - cache");
                PartialResponseWriter writer = ctx.getPartialViewContext()
                        .getPartialResponseWriter();
                writer.startDocument();
                writer.startEval();
                writer.write("alert(’Works!’);");
                writer.endEval();
                writer.endDocument();
                writer.flush();
                ctx.responseComplete();
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}
2
  • The response will be Javascript text. you need to pass it thru, eval to evaluate it. but that will be dangerous, why dont u just get plain data from json and do something based on that and keep the java script in the client ? Commented Jul 25, 2013 at 17:06
  • @Amogh: It's only dangerous if it contains inlined user-controlled input. Currently, it's just hardcoded in the server. Commented Jul 25, 2013 at 17:07

1 Answer 1

5
writer.write("alert(’Works!’);");

Curly quotes are not a valid string delimiter in JS. Use straight quotes.

writer.write("alert('Works!');");

Unrelated to the concrete problem, based on your question history you're using PrimeFaces, or at least familiar with it. In that case, just use RequestContext#execute() instead of this mess.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.