作为对 Ajax 请求的响应,我想返回立即在客户端上执行的 Javascript。我像这样尝试过,但它不起作用:
<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>
豆子:
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);
}
}
}
}