用coffeescript自动更新值



我是新的使用JS,所以我在这里有问题的rsrs

我需要自动更新结果字段,一旦用户开始在amount的字段上插入值

$(document).ready ->
$('form').submit ->
if $('form').attr('action') == '/convert'
$.ajax '/convert',
type: 'GET'
dataType: 'json'
data: {
source_currency: $("#source_currency").val(),
target_currency: $("#target_currency").val(),
amount: $("#amount").val()
}
error: (jqXHR, textStatus, errorThrown) ->
alert textStatus
success: (data, text, jqXHR) ->
$('#result').val(data.value)
return false;

现在我有一个提交按钮调用/convert但我怎么能擦除它,只是调用API只是当我收到的值,不完整或不

class ExchangeService
def initialize(source_currency, target_currency, amount)
@source_currency = source_currency
@target_currency = target_currency
@amount = amount.to_f
end

def call
value = get_exchange
value * @amount
rescue RestClient::ExceptionWithResponse => e
e.response
end
def get_exchange
exchange_api_url = Rails.application.credentials[Rails.env.to_sym][:currency_api_url]
exchange_api_key = Rails.application.credentials[Rails.env.to_sym][:currency_api_key]
url = "#{exchange_api_url}?token=#{exchange_api_key}&currency=#{@source_currency}/#{@target_currency}"
result = RestClient.get url
JSON.parse(result.body)['currency'][0]['value'].to_f
end
end

您可以在Rails中使用remote: true来发出AJAX请求:

一个Car资源的简单例子:

cars_controller.rb

def create
@car = Car.new(car_params)
respond_to do |format|
if @car.save
format.js
else
format.js
end
end
end

_form.html.erb

<%= form_with(model: car, local: false) do |form| %>
<% if car.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(car.errors.count, "error") %> prohibited this car from being saved:</h2>
<ul>
<% car.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>

create.js.erb

console.log('<%= @car.name  %>');

所以,当你提交你的rails表单时,请求会像JS一样。你的控制器需要接受这种格式(format.js),当数据被控制器处理时,流继续执行动作,但是在这个文件中使用js扩展(create.js.erb),你可以做你想做的,附加数据,替换数据,改变值,可以使用Ruby + js我希望这对你有用,原谅我糟糕的英语

最新更新