如何从控制器中检索GSP视图中的JSON对象

时间:2013-08-18 16:51:18

标签: json grails gsp

控制器有下一个方法(我正在回收bootstrap-file-upload plugin的实现):

def uploadImage() {     
    String baseName;
    String imageExtension = uploadPhotoService.imagesExtension;
    String thumbnailExtension = uploadPhotoService.thumbnailsExtension;

    switch(request.method){
        case "GET":

            def results = []    
            String imagesDirectoryPath = uploadPhotoService.getImageDirectoryDestinationPath(params.idAlojamiento);
            def dir = new File(imagesDirectoryPath)

            if( dir.exists() ) {
                dir.eachFile { 
                    baseName = uploadPhotoService.removeFileExtension(it.getName());

                    results << [
                            name: baseName,
                            size: it.length(),
                            url: createLink(controller:'alojamiento', action:'picture', params:[imageName: baseName + "." + imageExtension, idAlojamiento: params.idAlojamiento]),
                            thumbnail_url: createLink(controller:'alojamiento', action:'thumbnail', params:[imageName: baseName + "." + thumbnailExtension, idAlojamiento: params.idAlojamiento]),
                            delete_url: createLink(controller:'alojamiento', action:'deleteImage', params:[baseName: baseName, idAlojamiento: params.idAlojamiento]),
                            delete_type: "DELETE"
                    ]
                }
            }               
            render results as JSON
            break;
        case "POST":
            (...)

在视图中,有下一行:

<g:include controller="alojamiento" action="uploadImage" params="[idAlojamiento:alojamientoInstance.id]"/>

因此,Internet浏览器显示带有JSON结果变量内容的文本行:

[{"name":"boceto escaleras patio","size":37567,"url":"/AlojamientoPrototipo/alojamiento/picture?imageName=boceto+escaleras+patio.jpg&idAlojamiento=1","thumbnail_url":"/AlojamientoPrototipo/alojamiento/thumbnail?imageName=boceto+escaleras+patio.png&idAlojamiento=1","delete_url":"/AlojamientoPrototipo/alojamiento/deleteImage?baseName=boceto+escaleras+patio&idAlojamiento=1","delete_type":"DELETE"},
(...)

我不想显示该文字行。我想循环遍历所有图像。我认为它可行:

<g:each in="${results}">
    <img src="${it.thumbnail_url}"/>
</g:each>

如何将结果JSON变量传递给GSP视图以循环它?

1 个答案:

答案 0 :(得分:3)

获得这样的变量:

<g:set var="results" value="${g.include(controller: "alojamiento", action: "uploadImage", params: [idAlojamiento:alojamientoInstance.id])}" />  
<g:each in="${JSON.parse(results)}">
    <img src="${it.thumbnail_url}"/>
</g:each>

但是我应该提一下,你应该把它发送给初次通话。将逻辑放在服务中以使其可重用。

编辑:忘了它是一个字符串