make controller return HTML or JSON depending on request type

倖福魔咒の 提交于 2019-12-11 07:57:14

问题


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?


回答1:


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.




回答2:


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 }
    }
  }
}



回答3:


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.



来源:https://stackoverflow.com/questions/25497313/make-controller-return-html-or-json-depending-on-request-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!