2013-02-13 67 views
0

我试图从控制器操作中返回JSON。这是我的操作方法Grails从域列表怪异行为中呈现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呈现的页面。如果我删除它一切正常。

+0

你是什么意思“我的网页不会呈现”?你期望什么,会发生什么? – aiolos 2013-02-13 21:38:07

+0

我编辑了我的问题 – 2013-02-14 13:10:29

回答

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请求。

0

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