提问人:alcafar 提问时间:2/1/2013 更新时间:2/4/2013 访问量:3642
将 Javascript 变量传递给 Rails 部件
Passing Javascript variables to Rails partials
问:
我是 Rails 的新手,我正在为一项看似简单的任务而苦苦挣扎。 我有一个(精简的)表格:
<%= form_for @order, html: { :class => 'form-inline' } do |f| %>
<fieldset>
<legend><%= params[:action].capitalize %> Order</legend>
<table class="table">
<thead>
<tr>
<th><%= f.label :symbol %></th>
<th><%= f.label :price %></th>
</tr>
</thead>
<tbody>
<tr>
<td><%= f.text_field :symbol, class: 'input-small' %></td>
<td><%= f.text_field :price, class: 'input-small' %></td>
</tr>
</tbody>
</table>
<div id='here'></div>
<%= f.submit "Submit", class: "btn btn-primary" %>
</fieldset>
<% end %>
<%= link_to 'Get quote', view_quote_orders_path, remote: true %>
当我单击“获取报价”并且当符号文本字段失去焦点时,我想在 div $(#here) 中呈现谷歌金融中的报价。 我已经编写了代码来提取 Ruby 中的引文。
在 routes.rb 中,我添加了:
resources :orders do
get 'view_quote', on: :collection
end
在 order_controller.rb 中,我添加了:
def view_quote
respond_to do |format|
format.js { render :layout => false }
end
end
在 view_quote.js.erb 中:
sym = $('.orders #order_symbol').val();
$('#quotes').html("<%=j render 'googlequote', symbol: sym %>");
在 _googlequote.html.erb 中(我将把提取引文的逻辑放在那里):
<%= symbol %>
错误位于 view_quote.js.erb 中,因为 sym 未定义。 如果我将第二行替换为:
$('#quotes').html("<%=j render 'googlequote', symbol: 'just_a_test' %>");
部分被渲染,但我当然不需要它。 如何将 javascript 变量 sym 传递给部分 _googlequote.html.erb? 否则,有没有更好的方法来实现我的目标?
答:
你不能把它放在 erb 中,因为 erb 是在服务器上渲染的。实现此目的的一种方法是将符号用作 的参数,因此您可以得到类似以下内容的内容:view_quote
$('#quotes').html("<%=j render 'googlequote', symbol: params[:sym] %>");
(当然,你可以更 RESTfully 地连接该参数,但这是一个很好的起点)。
评论
您正在对 Orders 集合发出 GET 请求。这意味着所有这些。如果要使用订单模型中的符号,请向成员发出请求。
否则,您可以将其作为参数传递(我认为您正在尝试执行的操作)。如果你想在每次更改时都将其传递给服务器,我建议使用 jQuery 方法。然后你可以发出一个ajax请求:change
$.get('/orders', { sym: $('.orders #order_symbol').val() }, function(response) {
$('#here').html(response);
});
在控制器中:
def view_quote
@sym = params[:sym]
# use @sym in rendering partial
end
谢谢 @ben-taitelbaum 和 @ajcodez,最后我使用了不同的方法,在这篇优秀文章的示例 4 和 RyanonRails 的评论中提出了建议。
这样,在捕获符号字段更改事件后,符号被传递给控制器,在那里实现逻辑(从谷歌金融中抓取报价)。结果再次以 json 格式传递给 javascript 以插入到布局中。
评论