根据请求类型让控制器返回HTML或JSON [英] make controller return HTML or JSON depending on request type
问题描述
我想知道在Grails中是否有方法返回HTML或JSON,具体取决于我是否对某个操作进行了GET操作,或者是否只是通过Ajax调用操作。
例如,如果我对controller / action进行Ajax调用,是否有返回JSON的方法,如果通过链接进入相同的控制器/操作,则使其呈现HTML页面?或者我必须定义两个不同的动作?
通常,所有AJAX请求都有 X-Requested-With
标题集。你可以检查这个头是否被设置并且呈现所需的响应格式:
if(request.getHeader('X-Requested- ')){
$或者(正如Martin Hauner在评论中指出的那样)使用
//呈现响应为JSON
} else {
//渲染HTML页面
}
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 returnstrue
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.这篇关于根据请求类型让控制器返回HTML或JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!