如何从JavaScript中修改Rails脚本中的全局变量? [英] How do I modify a global variable in my Rails script from JavaScript?

查看:135
本文介绍了如何从JavaScript中修改Rails脚本中的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ PATH 
在我的Rails控制器中定义了以下变量: >





$ p



在JavaScript中,我想更改此变量的值: <脚本>
$(#resetDefaults)。click(function(){
$ PATH ='3'; //尝试1
<%= $ PATH%> ='3' ; //尝试2
});
< / script>

我已经尝试了上述两种说法,但无法弄清楚如何去做。

解决方案

全局变量只是在服务器上执行的Ruby代码中的全局

您在浏览器中运行JavaScript代码。该代码无法直接访问服务器上的变量。



如果您希望更改服务器上的某个状态(变量),则需要调用Rails控制器方法你的JavaScript代码。即,你需要从浏览器对服务器进行AJAX调用。像这样:

  $(#resetDefaults)。click(function(){
$ .ajax( {url:<%= url_for(:action =>'update_path_var')%>});
return false;
});

然后在控制器中有类似的东西:

  def update_path_var 
$ PATH = 1234
render:nothing => true
end

http://api.jquery.com/jQuery.ajax/

http://apidock.com/rails/ActionController/Base/url_for



顺便说一句,一般在Ruby中使用全局变量不被认为是良好的编码习惯,除非有一些非常具体的原因。


I have the following variable defined in my Rails controller:

$PATH

In JavaScript I would like to change the value of this variable:

<script>
   $("#resetDefaults").click(function(){
       $PATH = '3'; //try 1
       <%= $PATH %> = '3'; // try 2
   });
</script>

I have tried both of the above statements and can't figure out how to do it.

解决方案

A global variable is only global in the Ruby code that is executed on the server.

You're running JavaScript code in the browser. That code has no direct access to variables on the server.

If you wish to change some state (variable) on the server, you need to call a Rails controller method from your JavaScript code. I.e., you need to do an AJAX call to the server from the browser. Something like this:

$("#resetDefaults").click(function() {
   $.ajax({ url: "<%= url_for(:action => 'update_path_var') %>" });
   return false;
});

Then in the controller you have something like:

def update_path_var
  $PATH = 1234
  render :nothing => true
end

http://api.jquery.com/jQuery.ajax/
http://apidock.com/rails/ActionController/Base/url_for

BTW, in general using global variables in Ruby is not considered good coding practice, unless there is some very specific reason for it.

这篇关于如何从JavaScript中修改Rails脚本中的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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