如何在JSF中使用jQuery.post实现AJAX?

如何在JSF中使用jQuery.post实现AJAX?,ajax,jsf-2,Ajax,Jsf 2,我正试图使用jQuery.post从jsf页面向服务器发送一些数据。我已将同一页面的url作为处理请求的url。我能够获取数据,但无法将响应发送回我的jQuery.post呼叫 我的伪代码: jQuery.post('localhost/mypage.jsf', { data: 'xyz' }, function(res){ console.log(res); }); 我能够在处理程序类中获取数据变量,但无法返回响应 关于如何做得更好,有什么想法吗?JSF基本上是一个错误的工具。您应该

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

我的伪代码:

jQuery.post('localhost/mypage.jsf', { data: 'xyz' }, function(res){
    console.log(res);
});
我能够在处理程序类中获取
数据
变量,但无法返回响应


关于如何做得更好,有什么想法吗?

JSF基本上是一个错误的工具。您应该使用JAX-RS之类的web服务框架,而不是JSF之类的基于组件的MVC框架

但是,如果您真的坚持,您可以通过以下方式滥用JSF来发送任意响应。在视图中使用
在呈现视图之前调用一个方法,并将请求参数设置为bean属性(注意,这也有效地用于GET请求)

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

<f:metadata>
    <f:viewParam name="data" value="#{bean.data}" />
    <f:event type="preRenderView" listener="#{bean.process}" />
</f:metadata>
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.
}