javascript-根据表单输入生成动态网址
作者:互联网
我需要基于两个下拉输入(分别来自货币和两种货币)生成一个url,这样,当用户单击“提交”按钮时,生成货币时,生成的url应该看起来像http:// localhost:3000 / currencies / usd-eur是usd,而to_currency是eur.
这是我的观点(index.html.erb)
<%= semantic_form_for :calculator, :url => {:controller => "conversions", :action => "calculate" } do |f| %>
<p><%= f.label :amount %>
<%= f.text_field :amount %></p>
<p><%= f.label :from_currency %>
<%= select :calculator, :from_currency, Choices['from_currency'] %></p>
</p><%= f.label :to_currency %>
<%= select :calculator, :to_currency, Choices['to_currency'] %></p>
<p><%= f.submit "Calculate" %></p>
<%= end %>
routes.rb
match 'currencies', to: 'conversions#index', via: :get
match 'currencies/convert', to: 'conversions#calculate', as: :calculate, via: :post
控制器(conversions_controller.rb)
def index
end
def calculate
@amount = params[:calculator][:amount]
@from_cur = params[:calculator][:from_currency]
@to_cur = params[:calculator][:to_currency]
@result = ConversionsHelper.calculate(@from_cur, @to_cur, @amount)
end
我没有任何模型可以解决此问题,因为我是从Google API获取数据的,因此我可能会超出RESFFUL约定的范围.详细的答案将不胜感激.谢谢.
解决方法:
此javascript代码最终解决了我的问题.
$(document).ready(function(){
$('#Cal').attr('action', '/currencies');
$("#Cal").submit(function(e){
var from = $('#calculator_from_currency').val().toLowerCase();
var to = $('#calculator_to_currency').val().toLowerCase();
var url_end = from + "-" + to;
var url = $('#Cal').attr('action') + '/' + url_end;
$('#Cal').attr('action', url);
});
});
然后,我在路线中添加了这一行.
post '/currencies/:url' => 'conversions#calculate', via: [:post]
标签:ruby-on-rails-4,coffeescript,javascript,ruby-on-rails,jquery 来源: https://codeday.me/bug/20191030/1967361.html