简体   繁体   中英

How to assign and access a javascript variable in Rails using ajax

I'm using the gon gem for rails, which allows you to save variables defined in a controller action and use them in your JavaScript. It works fine when I use it in non-Ajax settings, however, I'm having an issue with using it successfully when doing Ajax requests.

The problem : Ruby variables I assign to gon variables in the controller action when making Ajax requests come out as 'undefined' in the JavaScript.

The objective : I want to trigger an Ajax request on my page, which: 1) hits an action in the controller, and assigns a Ruby variable to a gon variable. 2) it then renders a js.erb file which executes JavaScript, part of which needs to take the Ruby variable defined in step 1, and treat it as a js variable.

here's the example action in step 1 :

def some_action
 gon.my_ajax_var = {some: 'info'}
end

here's the example js.erb file it renders:

/some_action.js.erb

console.log('gon.my_ajax_var equals ' + gon.my_ajax_var)  //this doesn't work! comes out as 'undefined' when I expected {some: 'info'}

Any thoughts on how I fix this? I took a look at the gon.watch page, but I was confused as to whether that relates to this problem I'm having and how to implement the correct solution. Additionally, if there's a better way to do this without gon, I'm open to that as well.

Thanks!

I ended up solving this by doing the following:

In my controller:

def some_action
  @my_ajax_var = {some: 'info'}.to_json
end

In my corresponding view: /some_action.js.erb

var my_ajax_var = <%= @my_ajax_var.html_safe %>

Would've been nice to have piggybacked off the gon gem, but this got the job done.

It's some time ago that I used erb templates, but I think you need to add tags in your erb-file.

/some_action.js.erb

console.log('gon.my_ajax_var equals ' + <%= gon.my_ajax_var %>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM