如何在JSF使用jQuery.post实现AJAX? [英] How to implement AJAX using jQuery.post in JSF?

查看:802
本文介绍了如何在JSF使用jQuery.post实现AJAX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的JSF页面发送一些数据,使用 jQuery.post 服务器。我已经把同一个页面的URL作为URL处理该请求。我能够得到的数据,但无法发送回一个响应我的 jQuery.post 电话。

I'm trying to send some data from my jsf page to the server using jQuery.post. I have put the url of the same page as the url for handling the request. I'm able to get the data but not able to send a response back to my jQuery.post call.

我的伪code:

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

我能够得到我的处理程序类中的数据变量,但无法发送回一个响应。

I'm able to get the data variable in my handler class, but not able to send back a response.

我如何能做得更好任何想法?

Any ideas on how I can do it better?

推荐答案

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

JSF is basically the wrong tool for the job. You should be using a web service framework like JAX-RS instead of a component based MVC framework like JSF.

但如果你真的坚持,你可以滥用JSF发送任意的响应回下列方式。利用< F:事件类型=preRenderView> 在视图中调用一个方法的视图显示之前 < F:。viewParam> 来设置请求参数bean属性(请注意,这实际上也适用于GET请求)

But if you really insist, you could abuse JSF the following way to send an arbitrary response back. Make use of <f:event type="preRenderView"> in the view to invoke a method before the view is rendered and <f:viewParam> to set request parameters as bean properties (note that this effectively also works on GET requests).

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

通过类似下面的,如果你打算返回JSON与谷歌GSON帮助什么:

With something like the following if you intend to return JSON with help of Google Gson or something:

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 REST风格

这篇关于如何在JSF使用jQuery.post实现AJAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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