【发布时间】:2021-05-03 14:49:20
【问题描述】:
我是使用 JS 的新手,所以我在这里遇到问题 rsrs
我需要在用户开始在金额字段上插入值时自动更新结果字段
$(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}¤cy=#{@source_currency}/#{@target_currency}"
result = RestClient.get url
JSON.parse(result.body)['currency'][0]['value'].to_f
end
end
【问题讨论】:
-
您可以在表单中使用 remote: true 并跳过 AJAX 代码,然后使用 .js.erb 之类的视图来附加您的数据。
-
对不起,我没听懂,你能举个例子吗?
-
是的,我会在底部回答
-
您可以从您的输入元素中监听
input或change事件并使用它来触发AJAX 请求。$('#my-input').on 'input', ->而不是$('form').submit ->
标签: javascript ruby-on-rails ruby ajax coffeescript