faszynski
faszynski

Reputation: 439

Liferay + JSON + jQuery

I want get parameters from json, so I have a code:

    @RenderMode(name = "VIEW")
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws PortletException, IOException {
            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

            resourceRequest.setAttribute("resourceUrl", "http://localhost:8080/");

             jsonObject.put("rowsPerPage", 10);
             jsonObject.put("page", 1);
             jsonObject.put("total", 100);

             PrintWriter writer = resourceResponse.getWriter();
             writer.write(jsonObject.toString());
        }

What should be written in JavaScript method that displays the: rowsPerPage, page, total

I have a JavaScript code:

$.getJSON('http://localhost:8080/', function(jd) {
      alert(jd.rowsPerPage);
   });

JSP page:

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

<portlet:defineObjects />

This is the <portlet:resourceURL var="testURL" id="view.jsp" escapeXml="false" />
<br/><br/>
<div id="myGrid" style="width:600px;height:500px;"></div>
<div id="pager" style="width:600px;height:20px;"></div>

But it is wrong, why?

Upvotes: 0

Views: 3923

Answers (1)

Prakash K
Prakash K

Reputation: 11698

Check your URL http://localhost:8080/ if it returns a JSON response (you can directly paste the URL in the address bar of the Browser). This would return the Welcome page of Liferay.

For calling the serveResource method you would require a resourceURL to be passed in the jQuery function getJSON which can be generated using the <liferay-portlet:resourceURL> or <portlet:resourceURL> tags in JSP.

Update:

You should use the resourceURL in the javascript:

<portlet:resourceURL var="testURL" id="view.jsp" escapeXml="false" />

<script>
    $.getJSON('${testURL}', function(data) {
        alert(data.rowsPerPage);
    });
</scrip>

<!-- ${testURL}: This is EL i.e. expression language of JSP. Don't confuse it with jQuery -->
<!-- <%=testURL.toString() %>: You can also use scriptlet instead of using EL. But normally scriptlets as you might know are not recommended -->

Also I would like to suggest to make sure that the serveResource method is actually called with the script by included some log statements in the method.

Here are some links for examples as to how to use Ajax in Liferay:

  1. A working example to use Ajax in Liferay.
  2. Blog explaining concept as to how ajax works in a portal with a simple example.

Hope this helps.

Upvotes: 1

Related Questions