Monday, December 22, 2014

Create AJAX request and displaying JSON data in liferay

while loading the page means onload , create ajax request and getting json object from server is the below code: A.on('domready', function(event){
var allRows="";
//aui ajax call
A.io.request('<%=resourceURL%>',
{
dataType: 'json',
method: 'GET',
on: {
success: function() {
var data=this.get('responseData');
alert(data);
A.Array.each(data, function(obj, idx){
var tableRow=''+obj.Number+''+obj.Date+ ''+obj.Value+''+obj.VAT+''+obj.Total+'';
allRows=allRows+tableRow;
});
A.one('#usersTable').empty();
A.one('#usersTable').set('innerHTML',allRows);
}
}
});
});

In controller class - we need to implement serveResource() method :

the serveResourece method code is here:




@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException {
try {
List invoices =InvoiceLocalServiceUtil.getInvoices(0, InvoiceLocalServiceUtil.getInvoicesCount());
JSONArray invoiceJSONArray = JSONFactoryUtil.createJSONArray();
for(Invoice invoice : invoices){
JSONObject jsonObj = JSONFactoryUtil.createJSONObject();
jsonObj.put("Number", invoice.getInvoiceNo());
jsonObj.put("Date", invoice.getDateIssued());
jsonObj.put("Value", invoice.getValue());
jsonObj.put("VAT", invoice.getVat());
jsonObj.put("Total", invoice.getTotal());
invoiceJSONArray.put(jsonObj);
}

resourceResponse.getWriter().write(invoiceJSONArray.toString());
} catch (SystemException e) {
e.printStackTrace();
}
super.serveResource(resourceRequest, resourceResponse);
}

No comments:

Post a Comment