我正在使用select_tag
和onchange
。我需要调用辅助方法并将所选项目的值作为参数传递:
这就是我的辅助方法的样子
def find_template(temp)
"Hello #{temp}!"
end
我需要做的是使用 javascript 获取用户的选择,并将其传递给 find_template
。如果我传递一个字符串而不是模板,它就可以正常工作,即 <% @header = find_template("option_1") %>
但是当我使用var template
时我收到以下错误:
undefined local variable or method `template' for ...
这是我的 erb
<% content_for :javascript do %>
<script>
function template() {
var e = document.getElementById("category");
var template = e.options[e.selectedIndex].text;
<% @header = find_template(template) %>
}
</script>
<% end %>
<%= select_tag(:category, options_for_select(
Blah::TYPES.map {|k, v| [v['name'], k] }),
{onChange: 'template()'}) %>
<div id="template-overview">
<table>
<tr>
<% @header.each do |column| %>
<th class="<%= cycle('even', 'odd') -%>">
<%= column %>
</th>
<% end %>
</tr>
</table>
</div>
最佳答案
已解决:正确的方法是使用ajax:
在你的page.erb
<% content_for :javascript do %>
<script>
$(document).ready(function(){
$("#category").change(function(){
var temp_name = $('#category').val();
$.ajax({
url: "/YOUR_PATH/"+temp_name,
dataType: "html",
type: "GET",
data: {ANY_DATA: VALUES},
success: function(data){
jQuery("#template_overview").html(data);
}
});
});
});
</script>
<% end %>
<div id="template_overview">
</div>
有一个部分填充您的 div
在 Controller 中:
def display_template
.
.
.
.
render partial: '/PATH/template_overview', header: @header
end
当然还有路线
get 'controller/display_template/:temp_id' => 'controller#display_template'
关于javascript - 在 erb 中的 <% %> 内使用 javascript 变量 - Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38364780/