2013-02-13 44 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