I want to know if there is a way in Grails to return HTML or JSON depending if I make a GET to an action or if I just call an action through Ajax.
For example, if I make an Ajax call to "controller/action", is there a way to return JSON and if I go to the same "controller/action" trough a link, make it render an HTML page? or i have to define two diferent actions?
Yes its Possible,
if you difine in your controller
its a rough code, might be some mistakes but you get the idea..
Your Ajax Call will post data depend on the type
type:"POST"
ortype:"GET"
in your Ajax.. which you can get in controller. if controller sees that there is something posting then controller will do action accordingly. or if nothing is posted which you are looking for let controller send the HTML code.Typically all AJAX requests have
X-Requested-With
header set. You can check if this header is set and render desired format of response:Or (as Martin Hauner pointed out in comments) use
request.xhr
property which do basically the same and returnstrue
if current request is an AJAX:request
is an object representing current request. Read more about it in Grails documentation.withFormat builder is here to help: