当有 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 时,响应完全为空。仅发送标头。