根据请求类型让控制器返回HTML或JSON [英] make controller return HTML or JSON depending on request type

查看:152
本文介绍了根据请求类型让控制器返回HTML或JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Grails中是否有方法返回HTML或JSON,具体取决于我是否对某个操作进行了GET操作,或者是否只是通过Ajax调用操作。



例如,如果我对controller / action进行Ajax调用,是否有返回JSON的方法,如果通过链接进入相同的控制器/操作,则使其呈现HTML页面?或者我必须定义两个不同的动作?

解决方案

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

  if(request.getHeader('X-Requested- ')){
//呈现响应为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 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.

这篇关于根据请求类型让控制器返回HTML或JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆