且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据请求类型让控制器返回HTML或JSON

更新时间:2022-10-22 22:52:23

通常,所有AJAX请求都有 X-Requested-With 标题集。你可以检查这个头是否被设置并且呈现所需的响应格式:

  if(request.getHeader('X-Requested- ')){
//呈现响应为JSON
} else {
//渲染HTML页面
}
$或者(正如Martin Hauner在评论中指出的那样)使用 request.xhr 属性,它们基本相同并且返回 true 如果当前请求是AJAX:

  if(request.xhr ){
//将响应呈现为JSON
}其他{
//渲染HTML页面
}

request 是表示当前请求的对象。 在Grails文档中阅读更多关于它的内容。


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?

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.