开发者

Send javascript variables to rails?

开发者 https://www.devze.com 2023-02-25 14:05 出处:网络
I need to seed a javascript variable to the controll开发者_运维技巧er. For example, if my code in the view is the following -

I need to seed a javascript variable to the controll开发者_运维技巧er. For example, if my code in the view is the following -

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

I need the controller to get variable_test , like -

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

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


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.


First of all, you need to call the controller somehow. Either the data is in a form and you submit the form, or you make an AJAX call from javascript. In the first case, you'd want to use javascript to add a hidden input to the form with the name and value that you want. In the second case, the data you send with your AJAX request would need to include the name-value pair that you want. I can't get any more specific without knowing more about what you're doing; are you submitting a form or using AJAX, and if you're using AJAX are you using a javascript library, or using any of the built-in Rails helpers for ajax (e.g. remote_function).

Either way, though, you want to wind up with a request that includes the name-value pair "varliable_test=hello". Then you just do

@varliable_test = params[:varliable_test]

to access the value within your controller.

(I have to note, also, that presumably you mean "variable", not "varliable", but obviously that doesn't affect functionality so long as you're consistent.)


I was looking for an answer to this question, too. In one of my apps I need to grab data from Google's Places Autocomplete. This approach looks like a perfect solution to me (credit to Thaha kp: How to pass a javascript variable into a erb code in a js view?)

View:

<script type="text/javascript">
  var variable_test = 'hello';
  $(document).ready(function() {
    $('#model_variable_test').val(variable_test);
  });
</script>

...

<%= form_for :model do |f| %>
  ...
  <%= f.hidden_field :variable_test %>
  ...
<% end %>

Controller:

def hello
  @variable_test = params[:model][:variable_test]
end
0

精彩评论

暂无评论...
验证码 换一张
取 消