如何在 Rails 的 erb 代码中使用 JavaScript 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14080154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:39:22  来源:igfitidea点击:

How to use a JavaScript variable in erb code in Rails?

javascriptruby-on-rails

提问by Inaccessible

I have a JavaScript variable:

我有一个 JavaScript 变量:

var selectValUser = $('.select_user :selected').val();

I need to use this variable in erb code on the same page, i.e

我需要在同一页面上的erb代码中使用这个变量,即

<%= get_free_hours_for_user(selectValUser) %>

How can I do it?

我该怎么做?

回答by Muhamamd Awais

You cannot do it because javascript run on client side while the code in ERB file runs at server side, you can send the value using ajax request, Plus here is an awsome rails cast

您不能这样做,因为 javascript 在客户端运行,而 ERB 文件中的代码在服务器端运行,您可以使用 ajax 请求发送值,另外这里是一个 awsome rails cast

Here is an example to send message from javascript to controller; When user click on apply we have an action 'set_id' in controller, it get the power, do the validations etc, the show the message in 'id_message' div in views.

这是从 javascript 向控制器发送消息的示例;当用户点击应用时,我们在控制器中有一个动作“set_id”,它获得权力,进行验证等,在视图中的“id_message”div中显示消息。

  $('#apply').live('click', function(event, data, status, xhr) {
    event.preventDefault();
    return $.ajax({
      url: '/users/registrations/set_id',
      type: 'GET',
      data: {
        code: $('#user_id').val()
      },
      success: function(data, event, status, xhr) {
        $('#id_message').html(response);
        return $("#id_message").show();
      },
      error: function(event, data, status, xhr) {
        $('#id_message').html(response);
        return $("#id_message").show();
      }
    });
  });

Hope it would answer your question

希望它能回答你的问题

回答by LPD

There is no way to do it directly. Reason is, html runs in your server side whereas javascript runs in your local browser.

没有办法直接做到这一点。原因是,html 在您的服务器端运行,而 javascript 在您的本地浏览器中运行。

Additional discussion can be found here.

可以在此处找到其他讨论。

How to pass a javascript variable into a erb code in a js view?

如何在js视图中将javascript变量传递给erb代码?

And regarding different way to try it out, you can start with this.

关于尝试的不同方式,你可以从这个开始。

http://jing.io/t/pass-javascript-variables-to-rails-controller.html

http://jing.io/t/pass-javascript-variables-to-rails-controller.html

and

http://www.ruby-forum.com/topic/3818171

http://www.ruby-forum.com/topic/3818171