liferay的MVCPortlet的ajax请求

1.js

1
2
3
4
5
function redirectAndAjax(id){
    $.post('<%=ajaxUrl%>',{'<portlet:namespace/>id':id},function(data){
         alert(data);
         });
}

在页面上写JS引入JQUERY ,其中的ajaxUrl为在页面中定义的。定义代码为

1
<portlet:resourceURL var="ajaxUrl"/>

 

要在json的key前加入<portlet:namespace/> 否则后台无法收到传入的参数。

后台返回的值由js中的回调函数的data变量来接收。

jquery的文件为jquery-1.8.2.min.js 存放于 /docroot/js 目录下。

在jsp中的引入方式为在liferay-portlet.xml中的对应的portlet定义中的

1
<header-portlet-css>/css/main.css</header-portlet-css>

下加入行

1
<header-portlet-javascript>/js/jquery-1.8.2.min.js</header-portlet-javascript>

2.后台接收请求与返回值

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
@Override
    public void serveResource(ResourceRequest resourceRequest,
            ResourceResponse resourceResponse) throws IOException,
            PortletException {
        long id = ParamUtil.getLong(resourceRequest, "id",-1L);
                resourceResponse.setContentType("text/html;charset=UTF-8");
                PrintWriter out = null;
                try {
                  out = resourceResponse.getWriter();
               } catch (IOException e) {
                  e.printStackTrace();
               }
               String result = "这是服务端返回的结果信息:";
               out.println(result);
               out.flush();
               out.close();
 
}