gpt4 book ai didi

javascript - ajax Rails 表单计算器中的奇怪行为(预填充)

转载 作者:行者123 更新时间:2023-12-03 04:10:25 27 4
gpt4 key购买 nike

我有 ajax Rails 无数据库表单计算器。它工作得很好,但行为却很奇怪。我会尽力解释一下。

我转到/interest_calculator页面

用 10 填充@first_0

用 100 填充@second_0

我得到的结果等于:

数字 100 中的数字 50 = 50%

然后我进入根页面

返回/interest_calculator

重新加载页面,我的表单已预先填写了以前的值。我相信这是错误的行为。我的 JavaScript 知识非常基础,所以详细的回复会非常有帮助。

利息计算器 Controller :

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

我的 View 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 方法 而不是 GET。

首先,从 form_for 中删除 method: get (默认方法是 POST):

<%= form_for :interest_calculator, url: { action: :new }, remote: true do |f| %>

第二,更新你的路线:

post '/interest_calculator/new'

关于javascript - ajax Rails 表单计算器中的奇怪行为(预填充),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44355607/

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