有没有办法将javascript变量传递给html.erb中的ruby方法 [英] Is there a way to pass javascript variable into ruby method in html.erb

查看:80
本文介绍了有没有办法将javascript变量传递给html.erb中的ruby方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将变量传递给方法。以下是一个示例:

I'm trying to pass a variable into a method. Here is an example:

<script>
  var b = 1
  var c = "string" + "<%= method.a(b).to_s%>"
</script>

这不起作用。

这有效:

<% @b = 1%>
<script>
  var c = "string" + "<%= method.a(@b).to_s%>"
</script>

任何想法都会受到赞赏。

Any ideas would be appreciated.

推荐答案

您无法在Ruby方法中评估JavaScript变量。此外,您当前的脚本必须位于资产管道之外,这通常是一种不好的做法。

You can't evaluate a JavaScript variable inside your Ruby method. Also, your current script has to be outside the asset pipeline, which is usually a bad practice.

一个简单的解决方案是将变量作为数据属性传递。您将运行您的方法,然后在加载DOM后使用jQuery传递结果。这允许您将JavaScript保留在资产管道中并将其传递给Ruby服务器端评估的数据。

One simple solution is to pass the variable as a data attribute. You would run your method, then pass the result with jQuery after the DOM has loaded. This allows you to keep JavaScript in the asset pipeline and pass it data evaluated by Ruby server-side.

注意: @b 应在您的控制器上定义:

Note: @b should be defined on your controller:

<div id="foo" data-bar="<%= method.a(@b).to_s %>"></div>

<script>
  $(document).ready(function() {
    var b = $(#foo).data('bar');
    var c = "string" + b;
  });
</script>

另一个选项是使用不显眼的JavaScript

这篇关于有没有办法将javascript变量传递给html.erb中的ruby方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆