javascript - 在 GSP 中将数据从 Controller 传递到 JavaScript

标签 javascript json grails

我想直接在 View 中通过嵌入数据将数据从 Controller 传递到 javascript。 (因此不会有额外的请求。)

我的第一个解决方案是像这样在 GSP 中使用 as JSON:

<script>
  var data = ${invoice as JSON};
</script>

我不认为这是个好主意,因为我必须使用 (Grails 2.2)

grails.views.default.codec = "none"

或(Grails 2.3)

grails {
  views {
    gsp {
      codecs {
        expression = 'none'
      }
    }
  }
}

现在,我发现我可以像这样创建小标签库:

def json = { attrs, body ->
  out << (attrs.model as JSON)
}

我可以在 GSP 中使用以下代码:

<script>
  var data = <g:json model="${invoice}" />;
</script>

现在,问题。使用 taglib 是最佳实践吗?如果没有,请给我最好的解决方案。

最佳答案

转换评论中的答案。您可以在 Controller 中创建 JSON 字符串并将其传递给 View 。 Grails 2.3.x 具有不对您的内容进行编码的原始编解码器。有关此编解码器的更多信息 here .

例子:

class MyController {
  def index() {
    String invoiceString = invoice as JSON
    [json: invoiceString]
  }
}

index.gsp

<script>
  var data = ${raw(json)};
</script>

关于javascript - 在 GSP 中将数据从 Controller 传递到 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21452596/

相关文章:

c# - 在 C# 中解码嵌套 JSON 对象

javascript - Grails:AJAX onSuccess方法未触发

grails - Grails-验证传入数据和持久实例

javascript - 有没有办法在运行时重新启动 Node 服务器?

javascript - 使用单击事件为单个循环项添加和删除类

json - 使用 Alamofire 获取数组键值

testing - 在 Grails 中快速运行单个集成测试

javascript - 外部 Js 文件未加载

javascript - 像解析xml文件一样解析kml文件

php - URL 编码似乎妨碍了我的 PHP 程序中正确的 json 编码/解码