【问题标题】:Passing the model to a Javascript function through the onSuccess of a g:formRemote通过 g:formRemote 的 onSuccess 将模型传递给 Javascript 函数
【发布时间】:2014-04-16 22:33:28
【问题描述】:

我想在渲染模板后通过“onload()”函数调用 JS 函数,或者通过 g:formRemote 标记中的“onSuccess()”回调调用 JS 函数。在我的主要 GSP 中,我有以下内容。此代码对控制器进行回调并设置要传递到模板的模型。

GSP:
<g:formRemote name="ptoReport" url="[controller:'Report', action:'ptoBarChart']" update="barChartDiv">
    <g:submitButton name="pto" value="PTO" class="btn btn-primary"/>
</g:formRemote>

<div id="barChartDiv">
    <g:render template="barChart"/>
</div> 

我的控制器代码如下所示:

Controller:
def ptoBarChart(){
    Map usersAndPTO = timesheetService.getPTOForAllUsers()
    render(template: 'barChart', model:[points: usersAndPTO])
}

我想在模板加载后立即调用 JS 函数,但诀窍是将“usersAndPTO”映射传递给 JS 函数。我尝试将 "onLoad="barChart(${points})"" 添加到呈现的模板中,但它永远不会被调用。并将“onSuccess="barChart(data)"” 添加到 g:formRemote 会导致我将模板的 GSP 代码传递给 JS 函数。

非常感谢任何帮助。

【问题讨论】:

  • 你有没有想过将你需要的js添加到你的barChard.gsp中,它会在实际的dom中执行
  • 但我的目标是调用 JS 并传入模型。不确定我是否理解您的评论。
  • 我想在渲染完成后调用一个JS函数,使用模型中的数据。

标签: javascript jquery html grails grails-2.3


【解决方案1】:

看看这个:

在控制器中,我也会将点返回为 json,如果您只需要 js 将其渲染为 json

render(template: 'barChart', model:[points: usersAndPTO,jsonPoints: usersAndPTO as JSON])

这是你模板_barChart.gsp的底部

...
<g:if test="${jsonPoints}">
<script>

alert("${jsonPoints}");
// you can also pass them to a function from original dom, its available cause this template now is part of original dom
myFreakyFunction("${jsonPoints}");
</script>
</g:if>

当模板加载完成时,它应该会发出警报! 所以

【讨论】:

  • 漂亮!!!谢谢您的帮助。我发誓我一直在尝试一些非常相似的东西,但肯定就是这样。只需要得到一些友好的建议。顺便说一句,我选择了第一个选项。干杯。
  • 一千种通往罗马的方式,只要可行,欢迎您:D
猜你喜欢
  • 1970-01-01
  • 2021-08-15
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
相关资源
最近更新 更多