It is hard to find a web application that does not support Ajax these days. Mentawai makes it very easy for you to use Ajax by turning any action output in a JSON object that is sent back to the browser.
The Ajax browser request:
$.getJSON('<mtw:contextPath />/Hello.hi.mtw', function(actionOutput) { alert(actionOutput.msg); });
NOTE: We are using JQuery for client-side Ajax but you can use any library you want.
The action, like any other action:
public class HelloAction extends BaseAction { public String hi() { output.setValue("msg", "Hello there!"); return SUCCESS; } }
Setting up the Ajax consequence with a JSON renderer:
@Override public void loadActions() { action("/Hello", HelloAction.class, "hi") .on(SUCCESS, ajax(new JsonRenderer())); }
NOTE: Mentawai's JSON renderer can encode ANY object into JSON so feel free to add anything to the action output. That includes any collection of objects such as List and Map.
Returning lists as JSON:
public class HelloAction extends BaseAction { public String hi() { List<String> list = new LinkedList<String>(); list.add("Hello there!"); list.add("Hello again!"); output.setValue("msgs", list); return SUCCESS; } }
$.getJSON('<mtw:contextPath />/Hello.hi.mtw', function(actionOutput) { $.each(actionOutput.msgs, function(i,msg) { alert('item ' + i + ': ' + msg); }); });
Supporting Ajax and non-Ajax requests through the same action:
public class HelloAction extends BaseAction { public String hi() { output.setValue("msg", "Hello there!"); if (isAjaxRequest()) return AJAX; return SUCCESS; } }
@Override public void loadActions() { action("/Hello", HelloAction.class, "hi") .on(AJAX, ajax(new JsonRenderer())) .on(SUCESS, fwd("/jsp/hello.jsp")); }
Using a global filter to make any action support Ajax requests:
@Override public void loadFilters() { // for ALL actions, any request coming from Ajax will make the action return the AJAX result filter(new AjaxFilter(AJAX)); // and with the global consequence below, the action output will be returned as JSON on(AJAX, ajax(new JsonRenderer())); } }
TIP: An action specific consequence takes precedence over a global consequence. Therefore if you have an action that needs to set a different consequence for the AJAX result, feel free to do so.