发送JavaScript变量到Rails? [英] Send javascript variables to rails?
问题描述
我要种子一个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.
这篇关于发送JavaScript变量到Rails?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!