How do I modify a global variable in my Rails script from JavaScript?

核能气质少年 提交于 2019-12-11 19:21:03

问题


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.


回答1:


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.




回答2:


There is no way to achieve that. I think you should do some introduction to web programming course.



来源:https://stackoverflow.com/questions/17196173/how-do-i-modify-a-global-variable-in-my-rails-script-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!