简体   繁体   English

如何将JavaScript变量传递到Rails部分视图

[英]How to pass javascript variable to rails partial view

I got a situation, there is a Javascript variable I need pass to rails partial view. 我遇到一种情况,有一个Javascript变量需要传递给rails部分视图。

For example in test.html.erb 例如在test.html.erb中

<script type="text/javascript">
var array  =  <%= raw sort_section %>
    for(i = 0; i < array.length; i++) {
        $('#test').append("<%= j render :partial => 'section_in_panel', :locals => {:section => raw array[i]} %>");
    }
</script>

But it keep throwing syntax error, I have try many ways like 但是它不断抛出语法错误,我尝试了很多方法,例如

{:section => j sort_section_js[i]} %>"
{:section =>" + sort_section_js[i] + "}%>"

I need to use that because I want to call ajax to change array dynamically. 我需要使用它,因为我想调用ajax来动态更改array

Update 更新资料

So, maybe I need to write a controller 所以,也许我需要写一个控制器

def get_new_variable
    ...
    return new_variable
end 

Then in the test.html.erb 然后在test.html.erb中

<script>
$('test').onclick(function(event) {
   //write some ajax call
   //get new_variable
   $('#test').empty();
   $('#test').append("<%= j render :partial => 'section_in_panel', :locals => {:section => raw new_variable} %>");
  });
)</script>

Is that right direction? 那是正确的方向吗?

As Alberto Juan wrote in comment, you can't use javascript variable in ruby code. 正如Alberto Juan在评论中所写,您不能在ruby代码中使用javascript变量。 Ruby code will be interpreted before javascript and will not know what is the i. Ruby代码将在javascript之前解释,并且不知道i是什么。

Update: Your update will not work either as your using new_variable you get in your javascript code. 更新:您的更新将无法正常工作,因为您在JavaScript代码中使用new_variable。

For using partial after ajax call, follow instructions in this link 要在ajax调用后使用部分调用,请遵循此链接中的说明

Example: 例:

items/index.html.erb items / index.html.erb

<div class="grid">
  <% @categories.each do |cat| %>
    <%= link_to cat.name, fetch_items_path(:cat_id => cat.id), :remote => true %>
  <% end %>

  <%= render partial: 'item_grid', locals: { items: @items} %>
</div>

routes.rb routes.rb

get "/fetch_items" => 'items#from_category', as: 'fetch_items'

items_controller.rb items_controller.rb

def index
    @items = Item.all
    @categories = Category.all
end

def from_category
    @selected = Item.where(:category_id => params[:cat_id])
    respond_to do |format|
        format.js
    end
end

views/items/from_category.js.erb 视图/项目/from_category.js.erb

$("#items_grid").html("<%= escape_javascript(render partial: 'items_list', locals: { items: @selected } ) %>");  

You can use gem gon or simply do something like this: 您可以使用gem gon或简单地执行以下操作:

<script>
  MyVars[:someVar] = <%= some_value %>;
</script>

But, I recommend you to separate your backend an frontend code and use JSON for passing data to JS. 但是,我建议您分离后端代码,并使用JSON将数据传递给JS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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