简体   繁体   中英

Rails- Pass information from view to Javascript

I want to start using websockets. I read all the docs and understand everything, but it leaves out something I need: How to pass information from view to JS?

I need to pass data from javascript to my controller. What I do not understand is, how do I get dynamically generated data in my view to the javascript to be sent?

Right now my view receives an instance variable on every HTTP request, it loops over every instance variable and makes a button which submits a hash with information extracted from that instance variable. I do not understand how to do the same thing with Javascript because Javascript will not understand Ruby classes.

This is what my code looks like now:

View/dashboards/_other_characters.html.erb

<% other_characters.each do |other_character| %>
  <p><%= other_character.name %> is standing here (<%= other_character.power_level %>)</p>

  <%= button_to "punch #{other_character.name}",
    attacks_path(
      target_type: other_character.class,
      attack_type: :punch, 
      target_id: other_character,
      target_name: other_character.name
  ) %>
<% end %>

This is what I would like to be able to do using JS

var task = {
  name: 'Start taking advantage of WebSockets',
  completed: false
}
var dispatcher = new WebSocketRails('localhost:3000/websocket');
dispatcher.trigger('tasks.create', task);

Try

<%= button_to "punch #{other_character.name}",
  attacks_path(
    target_type: other_character.class,
    attack_type: :punch, 
    target_id: other_character,
    target_name: other_character.name
  ), {id: '***', data: {name: '***', other_key: 'other_value'} } %>

Then you can access the data via jQuery data api.

When you need get dynamic data from view by client js, add data-attrs in your view dom then read it from dom API or other 3rd party js API.

为了将信息从ruby传递到javascript,您可以使用以下gem: Gon ,基本上它可以转换ruby变量并使它们可用于每个视图上的javascript,请看一下: http : //railscasts.com/episodes/324-passing-数据到javascript来实现您的目的的任何其他替代方法,请访问: https : //www.ruby-toolbox.com/categories/javascript_tools#paloma

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