我有ajax rails没有数据库表单计算器。它运作良好,但是表现却很奇怪。我会尽力解释。
我转到/ interest_calculator页面
用10填充@ first_0
用100填充@ second_0
我得到的结果等于:
100中的50 = 50%
然后我进入根页面
返回到/ interest_calculator
重新加载页面,并且我的表单已预先填充了先前的值。我相信这是越野车的行为。我的JavaScript知识非常基础,因此详细的回复将非常有帮助。
InterestCalculator控制器:
class InterestCalculatorController < ApplicationController
def index
@result_0 = 0
end
def new
respond_to do |format|
format.html { render 'index.html.erb' }
format.js
end
# If accepted parameter is integer, then it shows in view as 5, when it
# is float, it shows as 5.1
@first_0 = params[:a_0].to_f % 1 != 0 ? params[:a_0].to_f : params[:a_0].to_i
@second_0 = params[:b_0].to_f % 1 != 0 ? params[:b_0].to_f : params[:b_0].to_i
# How many percent is number from the number
number_to_number(@first_0, @second_0)
end
private
def number_to_number(a = 0, b = 0)
# If the first number is zero, it sends 0% answer. If the second number is zero
# and the first number is nonzero, it sends infinity. Otherwise simple formula calculation.
if a.zero?
@result_0 = 0
elsif b.zero?
@result_0 = "infinity"
else
@result_0 = a.to_f / b.to_f * 100
end
end
end
我的观点index.html.erb
<div id="interest_calculator">
<%= form_for :interest_calculator, url: { action: :new }, method: :get, remote: true do |f| %>
<p>Сколько % составляет число</p>
<%= number_field_tag :a_0, params[:a_0], step: :any, id: "first_number_0" %>
<p>от числа</p>
<%= number_field_tag :b_0, params[:b_0], step: :any, id: "second_number_0" %>
<%= f.submit 'Calculate!', id: "number_to_number" %>
<% end %>
<% unless @result_0.nil? %>
<p>Number <span id="first_0"><%= @first_0 %></span> from number <span id="second_0"><%= @second_0 %></span> = <label id="answer_0"></label>%</p>
<% end %>
</div>
我的new.js.erb
document.getElementById("answer_0").innerHTML = "<%= @result_0 %>"
document.getElementById("first_0").innerHTML = "<%= @first_0 %>"
document.getElementById("second_0").innerHTML = "<%= @second_0 %>"
最佳答案
自动填充功能可能会为您预先填充值,请尝试在您的表单中将其禁用:
<%= form_for :interest_calculator, url: { action: :new }, method: :get, autocomplete: false, remote: true do |f| %>
另一个选择是使用POST
method
而不是GET。首先,从
method: get
中删除form_for
(默认方法是POST):<%= form_for :interest_calculator, url: { action: :new }, remote: true do |f| %>
其次,更新您的路线:
post '/interest_calculator/new'