【问题标题】:How to implement AJAX using jQuery.post in JSF?如何在 JSF 中使用 jQuery.post 实现 AJAX?
【发布时间】:2013-01-08 13:31:34
【问题描述】:

我正在尝试使用jQuery.post 将一些数据从我的jsf 页面发送到服务器。我已将同一页面的 url 与处理请求的 url 放在了一起。我能够获取数据,但无法将响应发送回我的jQuery.post 呼叫。

我的伪代码:

jQuery.post('localhost/mypage.jsf', { data: 'xyz' }, function(res){
    console.log(res);
});

我能够在我的处理程序类中获取 data 变量,但无法发回响应。

有什么想法可以让我做得更好吗?

【问题讨论】:

    标签: ajax jsf-2


    【解决方案1】:

    JSF 基本上是不适合这项工作的工具。您应该使用像 JAX-RS 这样的 Web 服务框架,而不是像 JSF 这样的基于组件的 MVC 框架。

    但是,如果您真的坚持,您可以通过以下方式滥用 JSF 来发送任意响应。在视图中使用 <f:event type="preRenderView"> 在视图呈现之前调用方法,并使用 <f:viewParam> 将请求参数设置为 bean 属性(请注意,这也适用于 GET 请求)。

    <f:metadata>
        <f:viewParam name="data" value="#{bean.data}" />
        <f:event type="preRenderView" listener="#{bean.process}" />
    </f:metadata>
    

    如果您打算在Google Gson 的帮助下返回 JSON,请使用类似以下内容:

    public void process() throws IOException {
        String message = "Hello! You have sent the following data: " + data;
        String json = new Gson().toJson(Collections.singletonMap("message", message));
    
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext ec = context.getExternalContext();
        ec.setResponseContentType("application/json");
        ec.setResponseCharacterEncoding("UTF-8");
        ec.getResponseOutputWriter().write(json);
        context.responseComplete(); // Prevent JSF from rendering the view.
    }
    

    同样,您滥用 JSF 作为工作的错误工具。看看 JAX-RS 或者甚至是一个普通的 servlet。另见Servlet vs RESTful

    【讨论】:

      猜你喜欢
      • 2012-11-08
      • 2011-03-09
      • 1970-01-01
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      相关资源
      最近更新 更多