且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从JavaScript中修改Rails脚本中的全局变量?

更新时间:2023-12-05 17:11:40

全局变量只是在服务器上执行的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.