简体   繁体   English

Ruby on Rails,实时计算

[英]Ruby on Rails, realtime calc

im learning RoR atm and im trying to code a calculator webapp. 即时通讯学习RoR atm和我试图编写计算器webapp。 The thing is: I want that the operations are gettin calculated in realtime. 问题是:我希望操作是实时计算的。 So if i type in 2+2 the calc says 4 without that i pressed some "CALC NOW" button. 因此,如果我键入2 + 2,则计算结果为4而没有按下我现在按下“立即计算”按钮。

Can someone give me some hints how i could to that? 有人可以给我一些提示我怎么能这样做? Do i need to learn AJAX for that? 我需要学习AJAX吗?

You can do the calculations on the client side using JavaScript only. 您只能使用JavaScript在客户端进行计算。 Or you can use JavaScript-driven automatic form submit or AJAX to send the input to the server and calculate with Ruby on Rails. 或者您可以使用JavaScript驱动的自动表单提交或AJAX将输入发送到服务器并使用Ruby on Rails进行计算。

To calculate on the server side: 要在服务器端计算:

routes: 路线:

resources :calculators

CalculatorsController CalculatorsController

def create
  @sum = eval(params[:data])
end

app/views/calculators/create.js.erb 应用程序/视图/计算器/ create.js.erb

document.getElementById("sum").innerHTML = <%= @sum %>

app/views/calculators/index.html.erb 应用程序/视图/计算器/ index.html.erb

<%= form_tag calculators_path, :method => :post, :remote => true do %>
  <%= text_field_tag :data, nil, :onkeyup => "this.form.sub.click()" %> = <span id="sum"></span>
  <%= submit_tag "ok", :name => "sub" %>
<% end %>

now go to /calculators and enjoy 现在去/calculators ,享受

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM