将Javascript变量传递给Rails局部函数 [英] Passing Javascript variables to Rails partials
问题描述
我是Rails的新手,我正在努力完成一项看似简单的任务. 我有一个(简化的)表格:
I am new in Rails and I am struggling on an apparently easy task. I have a (stripped down) form:
<%= 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)中的Google财务中提供报价. 我已经编写了用于提取Ruby中引号的代码.
I want to render the quotation in google finance in the div $(#here) when I click on 'Get quote' and when the symbol text field loses focus. I have already written the code to extract the quotation in Ruby.
在routes.rb中,我添加了:
In routes.rb I added:
resources :orders do
get 'view_quote', on: :collection
end
在order_controller.rb中,我添加了:
In order_controller.rb I added:
def view_quote
respond_to do |format|
format.js { render :layout => false }
end
end
并在view_quote.js.erb中:
and in view_quote.js.erb:
sym = $('.orders #order_symbol').val();
$('#quotes').html("<%=j render 'googlequote', symbol: sym %>");
和_googlequote.html.erb中(我将在其中放入提取引用的逻辑中):
and in _googlequote.html.erb (where I will put the logic to extract the quotation):
<%= symbol %>
该错误在view_quote.js.erb中,因为sym是未定义的. 如果我将第二行替换为:
The error is in view_quote.js.erb, because sym is undefined. If I replace the second line with:
$('#quotes').html("<%=j render 'googlequote', symbol: 'just_a_test' %>");
部分已渲染,但是我当然不需要它. 如何将javascript变量sym传递给部分_googlequote.html.erb? 否则,有没有更好的方法可以实现我的目标?
the partial is rendered, but of course I don't need it. How can I pass the javascript variable sym to the partial _googlequote.html.erb? Otherwise, is there a better way to accomplish my objective?
推荐答案
您不能将其放在erb中,因为erb在服务器上呈现.实现此目的的一种方法是将符号用作view_quote
的参数,因此您可能会遇到以下情况:
You can't put it in erb, because erb is rendered on the server. One way to accomplish this would be to use the symbol as a param to view_quote
, so you could have something like:
$('#quotes').html("<%=j render 'googlequote', symbol: params[:sym] %>");
(当然,您可以更REST地连接该参数,但这是一个不错的起点).
(of course, you can wire up that param more RESTfully, but this is a good starting point).
这篇关于将Javascript变量传递给Rails局部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!