grails - Grails:无法从 Controller 获取模型数据以进行查看

标签 grails grails-controller

最近3星期我一直在使用Grails(学习和工作)。我一直在尝试将JSP / Servlet应用程序移植到Grails,并且移植应用程序是绝对的“有趣”。

我遇到了一个问题,一直在搜索,阅读但仍无法解决。

在GSP页面中,我有一个文本字段和搜索按钮,用户可以在其中输入ProductID。当单击搜索按钮时,我有一个从jQuery Ajax方法调用的 Controller 。

// ----- jQuery Ajax调用的一部分---
$ .ajax({
类型:“发布”,
网址:“/ $ {grailsApplication.metadata ['app.name']} / product / checkProductAjax',
数据:“pid =” + proID,

// ----- Contoller代码-----
类ProductController {
def支架= true
def checkProductAjax = {
def product = Product.findByProductId(params.pid)
if(product){
[product:product] //用于在GSP页面中获取数据的模型。
渲染(product.toString()+“:” + product.id)
}其他{
渲染(“无”)
}
}
}

Ajax调用,一切正常。我面临的问题是如何获取模型(即产品数据返回到GSP页面,即[product:product]并在GSP中显示,例如产品名称:$ {product}

我该如何运作?我已经阅读了一些示例,其中提到仅设置模型[product:product]将有助于获取GSP中的数据。

产品名称:$ {product}在GSP页面中始终显示为空白产品名称:

请告诉我我做错了。

干杯!
杰伊·钱德兰

最佳答案

[product: product]render(product.toString() + ":" + product.id)不兼容。当您看到 Controller Action 的最后一行是类似于[product: product]的映射时,这是隐式返回值,因为它是 Action 关闭的最后一条语句-等效于return [product: product]。但是,如果您在方法中间有一个 map ,那么它将被创建并丢弃。它几乎等同于

def ignoreThisMap = [product: product]
// other code

由于您正在进行Ajax调用,因此将产品放入模型中没有意义,因为您不会重新渲染GSP。您将呈现文本,JSON,XML或客户端JavaScript将用来更新html的某些子集的其他内容。所以你可能想要更接近的东西
if (product) {
   render product as JSON
}
else {
   render "none"
}

然后您可以使用jQuery或Prototype评估JSON并提取JavaScript中的数据。

关于grails - Grails:无法从 Controller 获取模型数据以进行查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3614937/

相关文章:

grails - 渲染和响应自定义gson的不同(均为错误)输出

grails - 如何在Grails 3.1.7中使用i18n消息

grails - 我的 Controller 中无法访问域类

grails - 如何在Grails中使用withCriteria导致新的withCriteria查询?

grails - 在Grails 3(已确认3.2.6)中,具有空布局的渲染 View 无法正确覆盖默认值

grails - Grails平台核心,导航API:添加分隔符的简便方法?

java - 如何将GMetrics工具与Grails 3x应用程序集成

grails - 如何从Grails项目中删除App Engine插件

grails - Grails-如果值是负数,则将值显示为0

grails - 如何在Grails中设置 Restful Controller 脚手架