发送JavaScript变量到Rails?变量、JavaScript、Rails

2023-09-10 19:16:57 作者:℡中国好男儿゛

我要种子一个JavaScript变量控制器。例如,如果我的code的观点是如下 -

I need to seed a javascript variable to the controller. For example, if my code in the view is the following -

    ...  <script type="text/javascript">
           variable_test = 'hello'
         </script> 
    ...

我需要的控制器得到variable_test一样 -

I need the controller to get variable_test , like -

 def hello
 @variable_test = #Some code
 # @variable_test => 'hello'
 end

视图为hello当然,和有些code'是什么,我不知道该怎么办。

The view is hello of course, and 'Some code' is what I don't know how to do.

推荐答案

您不能发送客户端code到控制器,除非你做某种类型的获取,或交。尝试使用jQuery的POST或GET方法。如果你不使用jQuery,那么你可以做这样的事情:

You can't send client side code to the controller unless you do a get, or post, of some sort. Try using jQuery's post or get methods. If you aren't using jQuery then you can do something like this:

var variable_test = 'hello';
var el = document.createElement('script');
el.setAttribute('src', 'path_to_controller' + '?variable_test=' + variable_test);
document.body.appendChild(el);

然后在你的控制器,你会怎么做:

then in your controller you would do:

@varliable_test = params[:varliable_test]

语法可能有点过,但你得到的总体思路。

The syntax may be a bit off, but you get the general idea.

 
精彩推荐
图片推荐