作为对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);
}
}
}
}
答案 0 :(得分:5)
writer.write("alert(’Works!’);");
在JS中,curly引号不是有效的字符串分隔符。使用直引号。
writer.write("alert('Works!');");
不相关具体问题。在这种情况下,只需使用RequestContext#execute()
而不是这个混乱。