make controller return HTML or JSON depending on r

2019-08-07 06:49发布

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?

3条回答
做自己的国王
2楼-- · 2019-08-07 07:26

Yes its Possible,

if you difine in your controller

if(isset($_post) || isset(#_get)){
//if something is posted then this should execute
}
else
{
//this portion should execute..
}

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" or type:"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.

查看更多
爷、活的狠高调
3楼-- · 2019-08-07 07:46

Typically all AJAX requests have X-Requested-With header set. You can check if this header is set and render desired format of response:

if (request.getHeader('X-Requested-With')) {
    // render response as JSON
} else {
    // render HTML page
}

Or (as Martin Hauner pointed out in comments) use request.xhr property which do basically the same and returns true if current request is an AJAX:

if (request.xhr) {
    // render response as JSON
} else {
    // render HTML page
}

request is an object representing current request. Read more about it in Grails documentation.

查看更多
Bombasti
4楼-- · 2019-08-07 07:52

withFormat builder is here to help:

class BookController {

  def list() {
    def books = Book.list()

    withFormat {
        html bookList:books
        js { render books as JSON }
        xml { render books as XML }
    }
  }
}
查看更多
登录 后发表回答