0

当有 ajax 请求时,我想更改布局。所以我为此设置了一个过滤器:

class AjaxFilters {

def filters = {
    ajaxify(controller: '*', action: '*') {
        after = { Map model ->


    if(model==null) {
        model = new HashMap()
    }

    // only intercept AJAX requests
    if (!request.xhr) {
        model.put("layout", "mainUsers")
        return true 
    }

    // find our controller to see if the action is ajaxified
    def artefact = grailsApplication
        .getArtefactByLogicalPropertyName("Controller", controllerName)
    if (!artefact) { return true }

    // check if our action is ajaxified
    def isAjaxified = artefact.clazz.declaredFields.find {
        it.name == 'ajaxify'
    } != null


    def ajaxified = isAjaxified ? artefact.clazz?.ajaxify : []
    if (actionName in ajaxified || '*' in ajaxified) {
        model.put("layout", "ajax")
        return false
    }
    return true
        }
    }
}
}

这将创建一个名为“layout”的视图模型,它应该定义要使用的布局。

这是一个使用布局模型的示例视图:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<meta name="layout" content="${layout}"/>
<title>Profile</title>
</head>
<body>
<h3>Edit Profile</h3>
</body>
</html>

这是控制器:

class SettingsController {
def springSecurityService
static ajaxify = ["profile", "account"]

def profile() {
    User user = springSecurityService.currentUser

    UserProfile profile = UserProfile.findByUser(user)

    if(profile == null) {
        flash.error="Profile not found."
        return
    }

    [profile: profile, user: user]
}
}

正常请求按预期工作,但是当我尝试使用 ajax 时,响应完全为空。仅发送标头。

4

2 回答 2

1

对于将返回空白的 ajax 请求,您将返回 true 或 false。您应该使用渲染函数将模型对象转换为 JSON,或者将模型对象转换为 JSON 并返回。你不需要检查动作是否被 ajaxified;只需返回 JSON 对象。

于 2012-10-23T05:18:24.023 回答
1

在你之后,你model.put("layout", "ajax")不想回来false,而是true。返回false表示过滤器以某种方式失败并停止所有进一步的处理,这将导致向浏览器返回一个空响应。如果您返回true,更新后的模型将继续通过处理链并在您的 gsp 中呈现。

于 2012-10-23T13:26:41.807 回答