gpt4 book ai didi

jquery - 将 Javascript 变量传递给 Rails partials

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:57 24 4
gpt4 key购买 nike

我是 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) 中呈现 google finance 中的报价。我已经用 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 地连接该参数,但这是一个很好的起点)。

关于jquery - 将 Javascript 变量传递给 Rails partials,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14637242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com