如何将Javascript作为部分响应返回? [英] How to return Javascript as partial response?

查看:95
本文介绍了如何将Javascript作为部分响应返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为对Ajax请求的响应,我想立即返回在客户端上执行的Javascript。
我试过这样但它不起作用:

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>

豆子:

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);
            }
        }
    }
}


推荐答案

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

在JS中,curly引号不是有效的字符串分隔符。使用直引号。

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

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






不相关到具体问题,根据您使用PrimeFaces的问题历史记录,或者至少熟悉它。在这种情况下,只需使用 RequestContext #cute() 而不是这个烂摊子。


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.

这篇关于如何将Javascript作为部分响应返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆