【问题标题】:Grails rendering JSON from domain list weird behaviourGrails 从域列表中呈现 JSON 的奇怪行为
【发布时间】:2013-02-14 21:10:13
【问题描述】:

我正在尝试从控制器操作中返回 JSON。这是我的行动方法

import grails.converters.JSON
....    
def getDoctorList(id){

    def serviceNo = id ?: "1"


    def service = ServicePoint.findByNumber(serviceNo)

    def jsonMap=service?.staff.collect{
         [id: it.id , name: it.firstName +" "+ it.lastName]             
    }

    render jsonMap as JSON

   }

如果我在最后一行将 jsonMap 转换为 JSON,我的页面将不会被呈现,如果我在呈现 JSON 页面时删除并且一切正常。这段代码有什么问题?

================================================ ====================================

我不需要渲染 gsp 页面我需要将地图渲染为 json 以使用它来填充 gsp 页面中的下拉框。现在,当我在代码中使用(作为 JSON)时,不会显示由 ajax 呈现的页面。如果我删除它一切正常。

【问题讨论】:

  • “我的页面不会被渲染”是什么意思?您期望什么以及会发生什么?

标签: json grails


【解决方案1】:

通过呈现 JSON,您不会呈现与操作关联的模板。如果我假设约定并且您有一个 getDoctorList.gsp,那么以下内容将起作用:

def getDoctorList(id){
 //.. logic here
 // leaving no render method will default to convention
 // rendering getDoctorList.gsp
}

def getDoctorList(id){
 //.. logic here
 // supplying a render with a view will render that view
 render view: 'doctor_list' // assumes doctor_list.gsp
}

def getDoctorList(id){
 //.. logic here
 // Rendering JSON will not use a template at all
 render jsonMap as JSON
}

这会起作用,但我怀疑这是你想要的:

def getDoctorList(id){
 //.. logic here
 [jsonMap: jsonMap as JSON]
}

这会将 jsonMap 作为请求参数推送到 getDoctorList.gsp。一般来说,渲染 JSON 数据通常是为了响应一个 ajax 请求。

【讨论】:

    【解决方案2】:

    不是render jsonMap as JSON,而是return jsonMap as JSON。在第一种情况下,您在 Content-type 标头中返回 text/html,而 return Grails 将其设置为 application/json

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      相关资源
      最近更新 更多